from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session
from typing import List

from ..database import get_db
from ..models import Case
from ..schemas import CaseBase, CaseResponse

router = APIRouter(prefix="/api/admin/cases", tags=["admin"])

def get_current_admin(request: Request, db: Session = Depends(get_db)):
    """依赖项：验证管理员权限"""
    from .auth import verify_token
    auth_header = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="未提供认证令牌")
    token = auth_header.split(" ")[1]
    user = verify_token(token, db)
    if user.role != "admin":
        raise HTTPException(status_code=403, detail="需要管理员权限")
    return user

@router.get("", response_model=List[CaseResponse])
def list_cases(
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """获取案例列表（管理员）"""
    cases = db.query(Case).all()
    return [CaseResponse.model_validate(c) for c in cases]

@router.get("/{case_id}", response_model=CaseResponse)
def get_case(
    case_id: int,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """获取单个案例详情"""
    case = db.query(Case).filter(Case.id == case_id).first()
    if not case:
        raise HTTPException(status_code=404, detail="案例不存在")
    return case

@router.post("", response_model=CaseResponse)
def create_case(
    case_data: CaseBase,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """创建新案例"""
    case = Case(**case_data.model_dump())
    db.add(case)
    db.commit()
    db.refresh(case)
    return case

@router.put("/{case_id}", response_model=CaseResponse)
def update_case(
    case_id: int,
    case_update: CaseBase,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """更新案例"""
    case = db.query(Case).filter(Case.id == case_id).first()
    if not case:
        raise HTTPException(status_code=404, detail="案例不存在")
    update_data = case_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(case, field, value)
    db.commit()
    db.refresh(case)
    return case

@router.delete("/{case_id}")
def delete_case(
    case_id: int,
    request: Request,
    db: Session = Depends(get_db),
    admin_user = Depends(get_current_admin)
):
    """删除案例"""
    case = db.query(Case).filter(Case.id == case_id).first()
    if not case:
        raise HTTPException(status_code=404, detail="案例不存在")
    db.delete(case)
    db.commit()
    return {"message": "删除成功"}
