from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from models.calendars import TicketType

from datetime import datetime, timezone


def utcnow() -> datetime:
    return datetime.now(timezone.utc)


async def list_ticket_types(session: AsyncSession, entry_id: int) -> list[TicketType]:
    """Get all active ticket types for a calendar entry."""
    result = await session.execute(
        select(TicketType)
        .where(
            TicketType.entry_id == entry_id,
            TicketType.deleted_at.is_(None)
        )
        .order_by(TicketType.name)
    )
    return list(result.scalars().all())


async def create_ticket_type(
    session: AsyncSession,
    entry_id: int,
    *,
    name: str,
    cost: float,
    count: int,
) -> TicketType:
    """Create a new ticket type for a calendar entry."""
    ticket_type = TicketType(
        entry_id=entry_id,
        name=name,
        cost=cost,
        count=count,
        created_at=utcnow(),
        updated_at=utcnow(),
    )
    session.add(ticket_type)
    await session.flush()
    return ticket_type
