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.metadata import DatabaseOut, DataTableOut, DataColumnOut
from app.schemas.common import ResponseModel, ListResponse
from app.services import metadata_service
from app.api.deps import get_current_user, require_admin

router = APIRouter()


@router.get("/tree")
def get_tree(
    source_id: Optional[int] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    tree = metadata_service.build_tree(db, source_id=source_id)
    return ResponseModel(data=tree)


@router.get("/databases")
def list_databases(
    source_id: Optional[int] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items = metadata_service.list_databases(db, source_id=source_id)
    return ResponseModel(data=[DatabaseOut.model_validate(i) for i in items])


@router.get("/tables")
def list_tables(
    database_id: Optional[int] = Query(None),
    keyword: Optional[str] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items, total = metadata_service.list_tables(db, database_id=database_id, keyword=keyword)
    return ListResponse(data=[DataTableOut.model_validate(i) for i in items], total=total, page=1, page_size=len(items))


@router.get("/columns")
def list_columns(
    table_id: Optional[int] = Query(None),
    keyword: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=500),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items, total = metadata_service.list_columns(db, table_id=table_id, keyword=keyword, page=page, page_size=page_size)
    return ListResponse(data=[DataColumnOut.model_validate(i) for i in items], total=total, page=page, page_size=page_size)


@router.post("/sync/{source_id}")
def sync_metadata(
    source_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    result = metadata_service.sync_metadata(db, source_id, current_user.id)
    return ResponseModel(data=result)
