from __future__ import annotations

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

from app.db.base import utcnow
from app.db.models import SupportTicket


class SupportTicketService:
    def __init__(self, *, session_factory: async_sessionmaker[AsyncSession]) -> None:
        self._session_factory = session_factory

    async def create_ticket(
        self,
        *,
        public_id: str,
        telegram_id: int,
        username: str | None,
        display_name: str,
        user_message: str,
        support_chat_id: int,
        support_thread_id: int | None,
        support_message_id: int,
    ) -> SupportTicket:
        async with self._session_factory() as session:
            ticket = SupportTicket(
                public_id=public_id,
                telegram_id=telegram_id,
                username=username,
                display_name=display_name,
                user_message=user_message,
                support_chat_id=support_chat_id,
                support_thread_id=support_thread_id,
                support_message_id=support_message_id,
                status="OPEN",
            )
            session.add(ticket)
            await session.commit()
            await session.refresh(ticket)
            return ticket

    async def get_ticket_by_support_message(
        self,
        *,
        support_chat_id: int,
        support_message_id: int,
    ) -> SupportTicket | None:
        async with self._session_factory() as session:
            return await session.scalar(
                select(SupportTicket).where(
                    SupportTicket.support_chat_id == support_chat_id,
                    SupportTicket.support_message_id == support_message_id,
                )
            )

    async def mark_answered(self, *, ticket_id: int) -> None:
        async with self._session_factory() as session:
            ticket = await session.get(SupportTicket, ticket_id)
            if ticket is None:
                return

            ticket.status = "ANSWERED"
            ticket.updated_at = utcnow()
            await session.commit()

    async def get_open_tickets_count(self) -> int:
        async with self._session_factory() as session:
            total = await session.scalar(
                select(func.count(SupportTicket.id)).where(SupportTicket.status == "OPEN")
            )
        return int(total or 0)
