"""The app model — see app/crud/app_model.py."""

import uuid

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.permissions import deny_vendor, require_permission
from app.core.security import AuthContext, get_auth_context
from app.crud.app_model import build_model
from app.crud.base import CRUDBase
from app.models.app_bundle import App

router = APIRouter(tags=["app model"])
apps = CRUDBase(App)


@router.get("/app-model")
async def tenant_model(
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("apps", "view")),
    __: AuthContext = Depends(deny_vendor()),
) -> dict:
    """Everything in the tenant, as one model."""
    return await build_model(db, ctx.tenant_id)


@router.get("/apps/{app_id}/model")
async def app_model(
    app_id: uuid.UUID,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("apps", "view")),
    __: AuthContext = Depends(deny_vendor()),
) -> dict:
    """One app's items, and the entities they use, as one model."""
    return await build_model(db, ctx.tenant_id, await apps.get(db, ctx.tenant_id, app_id))
