"""打印模板 API（发货单 / 发票，按租户存储于数据库）"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from app.api.deps import get_db, require_permission
from app.core.models.user import User
from app.core.models.print_template import PrintTemplate

router = APIRouter(prefix="/admin/print-templates", tags=["打印模板"])

_VALID_KEYS = {"slip", "invoice", "receipt"}


class PrintTemplateIn(BaseModel):
    content: str


class PrintTemplateOut(BaseModel):
    key: str
    content: str
    is_custom: bool


async def _get(tenant_id: int, key: str, db: AsyncSession) -> PrintTemplate | None:
    r = await db.execute(
        select(PrintTemplate).where(
            PrintTemplate.tenant_id == tenant_id,
            PrintTemplate.template_key == key,
        )
    )
    return r.scalar_one_or_none()


@router.get("/{key}", response_model=PrintTemplateOut, summary="获取打印模板")
async def get_template(
    key: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission("settings.view")),
):
    if key not in _VALID_KEYS:
        raise HTTPException(404, "未知模板类型")
    tpl = await _get(current_user.tenant_id, key, db)
    return PrintTemplateOut(key=key, content=tpl.content if tpl else "", is_custom=tpl is not None)


@router.put("/{key}", response_model=PrintTemplateOut, summary="保存打印模板")
async def upsert_template(
    key: str,
    body: PrintTemplateIn,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission("settings.update")),
):
    if key not in _VALID_KEYS:
        raise HTTPException(404, "未知模板类型")
    tpl = await _get(current_user.tenant_id, key, db)
    if tpl:
        tpl.content = body.content
    else:
        tpl = PrintTemplate(
            tenant_id=current_user.tenant_id,
            template_key=key,
            content=body.content,
        )
        db.add(tpl)
    await db.commit()
    return PrintTemplateOut(key=key, content=tpl.content, is_custom=True)


@router.delete("/{key}", summary="重置打印模板为默认")
async def reset_template(
    key: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission("settings.update")),
):
    if key not in _VALID_KEYS:
        raise HTTPException(404, "未知模板类型")
    tpl = await _get(current_user.tenant_id, key, db)
    if tpl:
        await db.delete(tpl)
        await db.commit()
    return {"ok": True}
