"""OEM 桌面配置 CRUD（仅当前 OEM 数据）。"""

from fastapi import APIRouter, Query

from app.dependencies import OemUser, DbSession
from app.schemas.admin_desktop_config import (
    DesktopConfigCreate,
    DesktopConfigOut,
    DesktopConfigUpdate,
)
from app.schemas.common import ApiResponse, PaginatedData
from app.services import oem_desktop_config as config_service

router = APIRouter(prefix="/oem/desktop-configs", tags=["OEM-桌面配置"])


@router.get("", response_model=ApiResponse[PaginatedData[DesktopConfigOut]])
async def list_configs(
    oem: OemUser,
    db: DbSession,
    page: int = Query(1, ge=1),
    page_size: int = Query(
        config_service.DEFAULT_PAGE_SIZE,
        ge=1,
        le=config_service.MAX_PAGE_SIZE,
    ),
    keyword: str | None = Query(default=None, max_length=64, description="按键名模糊搜索"),
) -> ApiResponse[PaginatedData[DesktopConfigOut]]:
    rows, total = await config_service.list_configs(
        db,
        oem_user=oem,
        page=page,
        page_size=page_size,
        keyword=keyword,
    )
    return ApiResponse(
        ok=True,
        message="",
        data=PaginatedData.build(
            [DesktopConfigOut.model_validate(r) for r in rows],
            total=total,
            page=page,
            page_size=page_size,
        ),
    )


@router.post("", response_model=ApiResponse[DesktopConfigOut])
async def create_config(
    body: DesktopConfigCreate,
    oem: OemUser,
    db: DbSession,
) -> ApiResponse[DesktopConfigOut]:
    try:
        row = await config_service.create_config(db, body, oem_user=oem)
    except config_service.OemDesktopConfigError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(
        ok=True,
        message="配置已创建",
        data=DesktopConfigOut.model_validate(row),
    )


@router.patch("/{config_id}", response_model=ApiResponse[DesktopConfigOut])
async def update_config(
    config_id: int,
    body: DesktopConfigUpdate,
    oem: OemUser,
    db: DbSession,
) -> ApiResponse[DesktopConfigOut]:
    try:
        row = await config_service.update_config(db, config_id, body, oem_user=oem)
    except config_service.OemDesktopConfigError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(
        ok=True,
        message="配置已更新",
        data=DesktopConfigOut.model_validate(row),
    )


@router.delete("/{config_id}", response_model=ApiResponse[None])
async def delete_config(
    config_id: int,
    oem: OemUser,
    db: DbSession,
) -> ApiResponse[None]:
    try:
        await config_service.delete_config(db, config_id, oem_user=oem)
    except config_service.OemDesktopConfigError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(ok=True, message="配置已删除")
