"""Named dashboards CRUD router."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException

from media_library_viewer_api.dependencies import get_settings_store
from media_library_viewer_api.models.dashboards import NamedDashboard, NamedDashboardInput
from media_library_viewer_api.services.settings_store import SettingsStore

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


@router.get("")
def list_dashboards(store: SettingsStore = Depends(get_settings_store)) -> list[NamedDashboard]:
    rows = store.list_dashboards()
    return [NamedDashboard(**row) for row in rows]


@router.get("/slug/{slug}")
def get_dashboard_by_slug(slug: str, store: SettingsStore = Depends(get_settings_store)) -> NamedDashboard:
    row = store.get_dashboard_by_slug(slug)
    if not row:
        raise HTTPException(status_code=404, detail="Dashboard not found")
    return NamedDashboard(**row)


@router.post("")
def create_dashboard(body: NamedDashboardInput, store: SettingsStore = Depends(get_settings_store)) -> NamedDashboard:
    row = store.upsert_dashboard(body.model_dump())
    return NamedDashboard(**row)


@router.put("/{dashboard_id}")
def update_dashboard(
    dashboard_id: str,
    body: NamedDashboardInput,
    store: SettingsStore = Depends(get_settings_store),
) -> NamedDashboard:
    if not store.get_dashboard(dashboard_id):
        raise HTTPException(status_code=404, detail="Dashboard not found")
    if body.id and body.id != dashboard_id:
        raise HTTPException(status_code=400, detail="ID mismatch")
    row = store.upsert_dashboard(body.model_dump(), dashboard_id)
    return NamedDashboard(**row)


@router.delete("/{dashboard_id}")
def delete_dashboard(dashboard_id: str, store: SettingsStore = Depends(get_settings_store)) -> dict[str, str]:
    if not store.get_dashboard(dashboard_id):
        raise HTTPException(status_code=404, detail="Dashboard not found")
    store.delete_dashboard(dashboard_id)
    return {"status": "deleted"}
