from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from api.deps import get_current_user
from database.models import Seat, Ticket, TicketStatus, User
from database.session import get_db
from schemas.ticket import TicketResponse, TicketScanRequest, TicketScanResponse

router = APIRouter(prefix="/api/tickets", tags=["tickets"])


@router.get("/me", response_model=list[TicketResponse])
async def get_my_tickets(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> list[Ticket]:
    """Возвращает все оплаченные билеты текущего пользователя."""
    result = await db.execute(
        select(Ticket)
        .where(Ticket.user_id == current_user.id, Ticket.status == TicketStatus.PAID)
        .options(
            # Ticket → Seat → Tournament (один запрос на каждый уровень, без N+1)
            selectinload(Ticket.seat).selectinload(Seat.tournament)
        )
        .order_by(Ticket.created_at.desc())
    )
    return list(result.scalars().all())


@router.post("/scan", response_model=TicketScanResponse)
async def scan_ticket(
    body: TicketScanRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> TicketScanResponse:
    """
    Сканирует билет по secret_token (QR-код).
    Переводит статус PAID → SCANNED. Идемпотентно обрабатывает повторное сканирование.
    """
    result = await db.execute(
        select(Ticket).where(Ticket.secret_token == body.token)
    )
    ticket: Ticket | None = result.scalar_one_or_none()

    if ticket is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=TicketScanResponse(
                success=False,
                message="Билет не найден или подделка",
                ticket_id=None,
            ).model_dump(),
        )

    if ticket.status == TicketStatus.SCANNED:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=TicketScanResponse(
                success=False,
                message="Билет уже отсканирован!",
                ticket_id=ticket.id,
            ).model_dump(),
        )

    if ticket.status != TicketStatus.PAID:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=TicketScanResponse(
                success=False,
                message=f"Проход запрещен: статус билета '{ticket.status.value}'",
                ticket_id=ticket.id,
            ).model_dump(),
        )

    # PAID → SCANNED
    ticket.status = TicketStatus.SCANNED
    await db.commit()

    return TicketScanResponse(
        success=True,
        message="Проход разрешен",
        ticket_id=ticket.id,
    )
