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 (
    ExploreStateCreateIn,
    ExploreStateGetOut,
    ExploreStateListOut,
    ExploreStateUpdateIn,
)

dashboard_apps_router = APIRouter()


def _app_to_out(a: dict) -> dict:
    return {
        "id": a["id"],
        "type": a.get("type", ""),
        "updated_at": a.get("updated_at"),
        "created_at": a.get("created_at"),
        "state": a.get("state", {}),
    }


@dashboard_apps_router.get("/", response_model=ExploreStateListOut)
async def get_apps_api(db: FdbDb) -> list[dict]:
    apps = entities.list_dashboard_apps(db)
    return [_app_to_out(a) for a in apps]


@dashboard_apps_router.post("/", response_model=ExploreStateGetOut, status_code=201)
async def create_app_api(body: ExploreStateCreateIn, db: FdbDb) -> dict:
    a = entities.create_dashboard_app(db, body.type, state=body.state)
    return _app_to_out(a)


@dashboard_apps_router.get("/{app_id}/", response_model=ExploreStateGetOut)
async def get_app_api(app_id: str, db: FdbDb) -> dict:
    a = entities.get_dashboard_app(db, app_id)
    if not a:
        raise HTTPException(status_code=404)
    return _app_to_out(a)


@dashboard_apps_router.put("/{app_id}/", response_model=ExploreStateGetOut)
async def update_app_api(app_id: str, body: ExploreStateUpdateIn, db: FdbDb) -> dict:
    a = entities.get_dashboard_app(db, app_id)
    if not a:
        raise HTTPException(status_code=404)
    updates = {}
    if body.type is not None:
        updates["type"] = body.type
    if body.state is not None:
        updates["state"] = body.state
    if updates:
        entities.update_dashboard_app(db, app_id, **updates)
    updated = entities.get_dashboard_app(db, app_id)
    if not updated:
        raise HTTPException(status_code=404)
    return _app_to_out(updated)


@dashboard_apps_router.delete("/{app_id}/", status_code=204, response_model=None)
async def delete_app_api(app_id: str, db: FdbDb) -> None:
    a = entities.get_dashboard_app(db, app_id)
    if not a:
        raise HTTPException(status_code=404)
    entities.delete_dashboard_app(db, app_id)
