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

from ..database import get_db
from ..models import PlatformConfig
from ..schemas import PlatformConfigCreate, PlatformConfigUpdate, PlatformConfigResponse
from .auth import get_current_user

router = APIRouter(prefix="/api/platform-config", tags=["platform-config"])


@router.get("", response_model=List[PlatformConfigResponse])
def list_platforms(
    active_only: bool = True,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    query = db.query(PlatformConfig)
    if active_only:
        query = query.filter(PlatformConfig.is_active == True)
    return query.order_by(PlatformConfig.id).all()


@router.post("", response_model=PlatformConfigResponse)
def create_platform(
    data: PlatformConfigCreate,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    existing = db.query(PlatformConfig).filter(PlatformConfig.platform == data.platform).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"平台 '{data.platform}' 已存在")
    p = PlatformConfig(**data.model_dump())
    db.add(p)
    db.commit()
    db.refresh(p)
    return p


@router.get("/{platform}", response_model=PlatformConfigResponse)
def get_platform(platform: str, db: Session = Depends(get_db), current_user=Depends(get_current_user)):
    p = db.query(PlatformConfig).filter(PlatformConfig.platform == platform).first()
    if not p:
        raise HTTPException(status_code=404, detail="平台不存在")
    return p


@router.put("/{platform}", response_model=PlatformConfigResponse)
def update_platform(platform: str, data: PlatformConfigUpdate, db: Session = Depends(get_db), current_user=Depends(get_current_user)):
    p = db.query(PlatformConfig).filter(PlatformConfig.platform == platform).first()
    if not p:
        raise HTTPException(status_code=404, detail="平台不存在")
    for k, v in data.model_dump(exclude_unset=True).items():
        setattr(p, k, v)
    db.commit()
    db.refresh(p)
    return p


@router.delete("/{platform}")
def delete_platform(platform: str, db: Session = Depends(get_db), current_user=Depends(get_current_user)):
    p = db.query(PlatformConfig).filter(PlatformConfig.platform == platform).first()
    if not p:
        raise HTTPException(status_code=404, detail="平台不存在")
    p.is_active = False
    db.commit()
    return {"ok": True}