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

router = APIRouter()

@router.post("/api/v1/users/{user_id}/materials", tags=["用户素材管理"])
def upload_material(
    user_id: int,
    file: UploadFile = File(...),
    image_type: str = Form(...),
    original_filename: str = Form(...)
):
    """
    用户上传素材
    """
    file_bytes = file.file.read()
    result = user_material_service.upload_material(
        user_id=user_id,
        file_bytes=file_bytes,
        image_type=image_type,
        original_filename=original_filename
    )
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.get("/api/v1/users/{user_id}/materials", tags=["用户素材管理"])
def list_materials(
    user_id: int,
    material_type: Optional[str] = None,
    page: int = 1,
    page_size: int = 20
):
    """
    获取用户素材列表
    """
    result = user_material_service.list_materials(
        user_id=user_id,
        material_type=material_type,
        page=page,
        page_size=page_size
    )
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

from pydantic import BaseModel

class UpdateMaterialRequest(BaseModel):
    original_filename: str

@router.put("/api/v1/users/{user_id}/materials/{material_id}", tags=["用户素材管理"])
def update_material(
    user_id: int,
    material_id: int,
    data: UpdateMaterialRequest
):
    """
    更新用户素材信息
    """
    result = user_material_service.update_material(user_id, material_id, data.dict())
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.delete("/api/v1/users/{user_id}/materials/{material_id}", tags=["用户素材管理"])
def delete_material(
    user_id: int,
    material_id: int
):
    """
    删除用户素材
    """
    result = user_material_service.delete_material(user_id, material_id)
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result 