from fastapi import APIRouter, Query
from tortoise.expressions import Q

from app.controllers.policy import policy_controller
from app.schemas import Success, SuccessExtra
from app.schemas.policy import PolicyCreate, PolicyUpdate, PolicyResponse

router = APIRouter(tags=["政策管理"])


@router.get("/list", summary="查看政策列表")
async def list_policy(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    code: str = Query(None, description="政策代码"),
    name: str = Query(None, description="政策名称"),
    level: str = Query(None, description="政策级别"),
):
    q = Q()
    if code:
        q &= Q(code__contains=code)
    if name:
        q &= Q(name__contains=name)
    if level:
        q &= Q(level__contains=level)
    total, policy_objs = await policy_controller.list(page=page, page_size=page_size, search=q, order=["id"])
    data = [await obj.to_dict() for obj in policy_objs]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@router.get("/get", summary="查看政策详情")
async def get_policy(
    id: int = Query(..., description="政策 ID"),
):
    policy_obj = await policy_controller.get(id=id)
    data = await policy_obj.to_dict()
    return Success(data=data)


@router.post("/create", summary="创建政策")
async def create_policy(
    policy_in: PolicyCreate,
):
    # 检查代码是否已存在
    if await policy_controller.is_exist(policy_in.code):
        return Success(code=400, msg="政策代码已存在")
    
    await policy_controller.create(obj_in=policy_in)
    return Success(msg="创建成功")


@router.post("/update", summary="更新政策")
async def update_policy(
    policy_in: PolicyUpdate,
):
    # 检查代码是否已存在（排除当前记录）
    if policy_in.code:
        existing_obj = await policy_controller.model.filter(code=policy_in.code).exclude(id=policy_in.id).first()
        if existing_obj:
            return Success(code=400, msg="政策代码已存在")
    
    await policy_controller.update(id=policy_in.id, obj_in=policy_in)
    return Success(msg="更新成功")


@router.delete("/delete", summary="删除政策")
async def delete_policy(
    policy_id: int = Query(..., description="政策 ID"),
):
    await policy_controller.remove(id=policy_id)
    return Success(msg="删除成功")