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

from app.models.database import get_db
from app.schemas.user import APIKeyCreate, APIKeyResponse, APIKeyListResponse
from app.models.models import APIKey
from app.services.user import APIKeyService
from app.dependencies import get_current_active_user

# 创建路由器
router = APIRouter(prefix="/api-keys", tags=["api-keys"])


@router.post("", response_model=APIKeyResponse)
async def create_api_key(
    api_key_create: APIKeyCreate,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """创建API密钥"""
    # 只有管理员或用户本人可以为自己创建API密钥
    if current_user.role != "admin" and current_user.id != api_key_create.user_id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 创建API密钥
    api_key = APIKeyService.create_api_key(db, api_key_create)
    
    return api_key


@router.get("", response_model=APIKeyListResponse)
async def get_api_keys(
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取API密钥列表"""
    # 管理员可以查看所有API密钥，普通用户只能查看自己的
    if current_user.role == "admin":
        # 这里可以添加分页和过滤，暂时返回所有
        api_keys = db.query(APIKey).all()
    else:
        api_keys = APIKeyService.get_api_keys_by_user_id(db, current_user.id)
    
    return {"api_keys": api_keys, "total": len(api_keys)}


@router.get("/{api_key_id}", response_model=APIKeyResponse)
async def get_api_key(
    api_key_id: str,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取API密钥详情"""
    # 获取API密钥
    api_key = APIKeyService.get_api_key_by_id(db, api_key_id)
    if not api_key:
        raise HTTPException(status_code=404, detail="API key not found")
    
    # 管理员可以查看所有API密钥，普通用户只能查看自己的
    if current_user.role != "admin" and current_user.id != api_key.user_id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    return api_key


@router.delete("/{api_key_id}", response_model=dict)
async def revoke_api_key(
    api_key_id: str,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """撤销API密钥"""
    # 获取API密钥
    api_key = APIKeyService.get_api_key_by_id(db, api_key_id)
    if not api_key:
        raise HTTPException(status_code=404, detail="API key not found")
    
    # 管理员可以撤销所有API密钥，普通用户只能撤销自己的
    if current_user.role != "admin" and current_user.id != api_key.user_id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 撤销API密钥
    result = APIKeyService.revoke_api_key(db, api_key_id)
    if not result:
        raise HTTPException(status_code=400, detail="Failed to revoke API key")
    
    return {"message": "API key revoked successfully"}
