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

from app.core.database import get_db
from app.models.user import User
from app.schemas.datasource import DataSourceCreate, DataSourceUpdate, DataSourceOut, DataSourceTest
from app.schemas.common import ResponseModel, ListResponse
from app.services import datasource_service
from app.api.deps import get_current_user, require_admin

router = APIRouter()


@router.get("", response_model=ListResponse[DataSourceOut])
def list_datasources(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=500),
    keyword: Optional[str] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items, total = datasource_service.list_datasources(db, keyword=keyword, page=page, page_size=page_size)
    return ListResponse(data=[DataSourceOut.model_validate(i) for i in items], total=total, page=page, page_size=page_size)


@router.get("/{source_id}", response_model=ResponseModel[DataSourceOut])
def get_datasource(
    source_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    item = datasource_service.get_datasource(db, source_id)
    if not item:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="数据源不存在")
    return ResponseModel(data=DataSourceOut.model_validate(item))


@router.post("", response_model=ResponseModel[DataSourceOut])
def create_datasource(
    req: DataSourceCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    item = datasource_service.create_datasource(db, req, current_user.id)
    return ResponseModel(data=DataSourceOut.model_validate(item))


@router.put("/{source_id}", response_model=ResponseModel[DataSourceOut])
def update_datasource(
    source_id: int,
    req: DataSourceUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    db_obj = datasource_service.get_datasource(db, source_id)
    if not db_obj:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="数据源不存在")
    item = datasource_service.update_datasource(db, db_obj, req)
    return ResponseModel(data=DataSourceOut.model_validate(item))


@router.delete("/{source_id}")
def delete_datasource(
    source_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    datasource_service.delete_datasource(db, source_id)
    return ResponseModel(message="删除成功")


@router.post("/test-connection")
def test_connection(
    req: DataSourceTest,
    current_user: User = Depends(get_current_user),
):
    result = datasource_service.test_connection(req)
    return ResponseModel(data=result)
