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.common import ResponseModel, ListResponse
from app.models.schema_change import SchemaChangeLog
from app.api.deps import get_current_user

router = APIRouter()


@router.get("/logs")
def list_schema_changes(
    source_id: Optional[int] = Query(None),
    change_type: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=500),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    query = db.query(SchemaChangeLog)
    if source_id:
        query = query.filter(SchemaChangeLog.source_id == source_id)
    if change_type:
        query = query.filter(SchemaChangeLog.change_type == change_type)
    total = query.count()
    items = query.order_by(SchemaChangeLog.detected_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
    return ListResponse(
        data=[{
            "id": log.id,
            "source_id": log.source_id,
            "database_id": log.database_id,
            "table_id": log.table_id,
            "column_id": log.column_id,
            "change_type": log.change_type,
            "old_value": log.old_value,
            "new_value": log.new_value,
            "detected_at": log.detected_at.isoformat() if log.detected_at else None,
        } for log in items],
        total=total,
        page=page,
        page_size=page_size,
    )
