from __future__ import annotations

from fastapi import APIRouter, HTTPException

from matyan_backend.deps import FdbDb  # noqa: TC001
from matyan_backend.storage import entities

from .pydantic_models import ReportCreateIn, ReportListOut, ReportOut, ReportUpdateIn

reports_router = APIRouter()


def _report_to_out(r: dict) -> dict:
    return {
        "id": r["id"],
        "name": r.get("name", ""),
        "code": r.get("code"),
        "description": r.get("description"),
        "updated_at": r.get("updated_at"),
        "created_at": r.get("created_at"),
    }


@reports_router.get("/", response_model=ReportListOut)
async def get_reports_api(db: FdbDb) -> list[dict]:
    reports = entities.list_reports(db)
    return [_report_to_out(r) for r in reports]


@reports_router.post("/", response_model=ReportOut, status_code=201)
async def create_report_api(body: ReportCreateIn, db: FdbDb) -> dict:
    r = entities.create_report(db, body.name, code=body.code, description=body.description)
    return _report_to_out(r)


@reports_router.get("/{report_id}/", response_model=ReportOut)
async def get_report_api(report_id: str, db: FdbDb) -> dict:
    r = entities.get_report(db, report_id)
    if not r:
        raise HTTPException(status_code=404)
    return _report_to_out(r)


@reports_router.put("/{report_id}/", response_model=ReportOut)
async def update_report_api(report_id: str, body: ReportUpdateIn, db: FdbDb) -> dict:
    r = entities.get_report(db, report_id)
    if not r:
        raise HTTPException(status_code=404)
    updates = {}
    if body.name is not None:
        updates["name"] = body.name
    if body.code is not None:
        updates["code"] = body.code
    if body.description is not None:
        updates["description"] = body.description
    if updates:
        entities.update_report(db, report_id, **updates)
    updated = entities.get_report(db, report_id)
    if not updated:
        raise HTTPException(status_code=404)
    return _report_to_out(updated)


@reports_router.delete("/{report_id}/", status_code=204, response_model=None)
async def delete_report_api(report_id: str, db: FdbDb) -> None:
    r = entities.get_report(db, report_id)
    if not r:
        raise HTTPException(status_code=404)
    entities.delete_report(db, report_id)
