from fastapi import APIRouter, Depends, HTTPException, Form, File
from fastapi.responses import JSONResponse
from typing import Optional
from backend.services.user_template_service import user_template_service

router = APIRouter()

@router.post("/api/v1/users/{user_id}/templates", tags=["用户文本模板管理"])
def create_text_template(
    user_id: int,
    text_type: str = Form(...),
    text_name: str = Form(...),
    text_label: str = Form(...),
    text_content: str = Form(...)
):
    """
    创建文本模板
    """
    result = user_template_service.create_text_template(
        user_id=user_id,
        text_type=text_type,
        text_name=text_name,
        text_label=text_label,
        text_content=text_content
    )
    if not result["success"]:   
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.get("/api/v1/users/{user_id}/templates", tags=["用户文本模板管理"])
def list_text_templates(
    user_id: int,
    text_type: Optional[str] = None,
    page: int = 1,
    page_size: int = 20
):
    """
    获取用户文本模板列表
    """
    result = user_template_service.list_text_templates(
        user_id=user_id,
        text_type=text_type,
        page=page,
        page_size=page_size
    )
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.delete("/api/v1/users/{user_id}/templates/{text_id}", tags=["用户文本模板管理"])
def delete_text_template(
    user_id: int,
    text_id: int
):
    """
    删除文本模板
    """
    result = user_template_service.delete_text_template(
        user_id=user_id,
        text_id=text_id
    )
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.put("/api/v1/users/{user_id}/templates/{text_id}", tags=["用户文本模板管理"])
def update_text_template(
    user_id: int,
    text_id: int,
    text_type: Optional[str] = Form(None),
    text_name: Optional[str] = Form(None),
    text_label: Optional[str] = Form(None),
    text_content: Optional[str] = Form(None)
):
    """
    更新文本模板（任意字段可选，提供则更新）
    """
    data = {}
    if text_type is not None:
        data["text_type"] = text_type
    if text_name is not None:
        data["text_name"] = text_name
    if text_label is not None:
        data["text_label"] = text_label
    if text_content is not None:
        data["text_content"] = text_content

    if not data:
        return {"success": True, "message": "无更新字段"}

    result = user_template_service.update_text_template(
        user_id=user_id,
        text_id=text_id,
        data=data
    )
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result