from __future__ import annotations

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

from models.calendars import TicketType

from datetime import datetime, timezone


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


async def get_ticket_type(session: AsyncSession, ticket_type_id: int) -> TicketType | None:
    """Get a single ticket type by ID (only if not soft-deleted)."""
    result = await session.execute(
        select(TicketType)
        .where(
            TicketType.id == ticket_type_id,
            TicketType.deleted_at.is_(None)
        )
    )
    return result.scalar_one_or_none()


async def update_ticket_type(
    session: AsyncSession,
    ticket_type_id: int,
    *,
    name: str,
    cost: float,
    count: int,
) -> TicketType | None:
    """Update an existing ticket type."""
    ticket_type = await get_ticket_type(session, ticket_type_id)
    if not ticket_type:
        return None

    ticket_type.name = name
    ticket_type.cost = cost
    ticket_type.count = count
    ticket_type.updated_at = utcnow()

    await session.flush()
    return ticket_type


async def soft_delete_ticket_type(session: AsyncSession, ticket_type_id: int) -> bool:
    """Soft-delete a ticket type."""
    ticket_type = await get_ticket_type(session, ticket_type_id)
    if not ticket_type:
        return False

    ticket_type.deleted_at = utcnow()
    await session.flush()
    return True
