"""Unit tests for ticket grouping logic."""
from __future__ import annotations

from types import SimpleNamespace
from datetime import datetime

import pytest

from cart.bp.cart.services.ticket_groups import group_tickets


def _ticket(entry_id=1, entry_name="Event", ticket_type_id=None,
            ticket_type_name=None, price=10.0,
            entry_start_at=None, entry_end_at=None):
    return SimpleNamespace(
        entry_id=entry_id,
        entry_name=entry_name,
        entry_start_at=entry_start_at or datetime(2025, 6, 1, 10, 0),
        entry_end_at=entry_end_at,
        ticket_type_id=ticket_type_id,
        ticket_type_name=ticket_type_name,
        price=price,
    )


class TestGroupTickets:
    def test_empty(self):
        assert group_tickets([]) == []

    def test_single_ticket(self):
        result = group_tickets([_ticket()])
        assert len(result) == 1
        assert result[0]["quantity"] == 1
        assert result[0]["line_total"] == 10.0

    def test_same_group_merged(self):
        tickets = [_ticket(entry_id=1), _ticket(entry_id=1)]
        result = group_tickets(tickets)
        assert len(result) == 1
        assert result[0]["quantity"] == 2
        assert result[0]["line_total"] == 20.0

    def test_different_entries_separate(self):
        tickets = [_ticket(entry_id=1), _ticket(entry_id=2)]
        result = group_tickets(tickets)
        assert len(result) == 2

    def test_different_ticket_types_separate(self):
        tickets = [
            _ticket(entry_id=1, ticket_type_id=1, ticket_type_name="Adult"),
            _ticket(entry_id=1, ticket_type_id=2, ticket_type_name="Child"),
        ]
        result = group_tickets(tickets)
        assert len(result) == 2

    def test_none_price(self):
        result = group_tickets([_ticket(price=None)])
        assert result[0]["line_total"] == 0.0

    def test_ordering_preserved(self):
        tickets = [
            _ticket(entry_id=2, entry_name="Second"),
            _ticket(entry_id=1, entry_name="First"),
        ]
        result = group_tickets(tickets)
        assert result[0]["entry_name"] == "Second"
        assert result[1]["entry_name"] == "First"

    def test_metadata_from_first_ticket(self):
        tickets = [
            _ticket(entry_id=1, entry_name="A", price=5.0),
            _ticket(entry_id=1, entry_name="B", price=10.0),
        ]
        result = group_tickets(tickets)
        assert result[0]["entry_name"] == "A"  # from first
        assert result[0]["price"] == 5.0  # from first
        assert result[0]["line_total"] == 15.0  # accumulated
