"""Rotas API do registry de módulos."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from app import auth
from app.modules import store

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


class ModuleToggle(BaseModel):
    enabled: bool


@router.get("")
def list_modules(user: auth.DeskUser = Depends(auth.get_current_user)):
    return {"modules": store.list_modules()}


@router.patch("/{module_id}")
def set_module(
    module_id: str,
    body: ModuleToggle,
    user: auth.DeskUser = Depends(auth.get_current_user),
):
    if user.role != "super_admin":
        raise HTTPException(403, "insufficient permissions")
    try:
        store.set_module_enabled(module_id, body.enabled)
    except KeyError:
        raise HTTPException(404, "module not found") from None
    except ValueError as exc:
        raise HTTPException(400, str(exc)) from exc
    return {"id": module_id, "enabled": store.is_module_enabled(module_id)}
