from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse

from admin.auth import require_admin
from admin.templates_env import templates
from database.queries.ticket_attachments import get_attachments
from database.queries.tickets import get_all_tickets, get_ticket, update_ticket_status
from database.queries.organizations import get_all_organizations

router = APIRouter(prefix="/tickets", dependencies=[Depends(require_admin)])


@router.get("", response_class=HTMLResponse)
async def list_tickets(
    request: Request,
    org_id: int | None = None,
    status: str | None = None,
):
    tickets = await get_all_tickets(org_id=org_id, status=status)
    orgs = await get_all_organizations()
    return templates.TemplateResponse(
        request=request,
        name="tickets/list.html",
        context={
            "tickets": tickets,
            "orgs": orgs,
            "filter_org_id": org_id,
            "filter_status": status,
        },
    )


@router.get("/{ticket_id}", response_class=HTMLResponse)
async def ticket_detail(request: Request, ticket_id: int):
    ticket = await get_ticket(ticket_id)
    attachments = await get_attachments(ticket_id)
    return templates.TemplateResponse(
        request=request,
        name="tickets/detail.html",
        context={"ticket": ticket, "attachments": attachments},
    )


@router.post("/{ticket_id}/status")
async def update_status(
    ticket_id: int,
    status: str = Form(...),
    last_comment: str = Form(""),
):
    await update_ticket_status(
        ticket_id=ticket_id,
        status=status,
        last_comment=last_comment or None,
    )
    return RedirectResponse(f"/admin/tickets/{ticket_id}", status_code=303)
