# app/modules/dev_tools/routes/api/admin_sql_query.py
"""
SQL Query API endpoints.

All endpoints require super-admin authentication via Bearer token.
"""

import logging

from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session

from app.api.deps import UserContext, get_current_super_admin_api, get_db
from app.modules.dev_tools.services.sql_query_service import (
    create_saved_query,
    delete_saved_query,
    execute_query,
    list_saved_queries,
    record_query_run,
    update_saved_query,
)

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/sql-query", tags=["sql-query"])


# ---------------------------------------------------------------------------
# Schemas
# ---------------------------------------------------------------------------


class ExecuteRequest(BaseModel):
    sql: str = Field(..., min_length=1, max_length=10000)
    saved_query_id: int | None = None


class SavedQueryCreate(BaseModel):
    name: str = Field(..., min_length=1, max_length=200)
    sql_text: str = Field(..., min_length=1, max_length=10000)
    description: str | None = None


class SavedQueryUpdate(BaseModel):
    name: str | None = Field(None, min_length=1, max_length=200)
    sql_text: str | None = Field(None, min_length=1, max_length=10000)
    description: str | None = None


# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------


@router.post("/execute")  # noqa: API001
async def execute_sql(
    body: ExecuteRequest,
    ctx: UserContext = Depends(get_current_super_admin_api),
    db: Session = Depends(get_db),
):
    """Execute a read-only SQL query."""
    result = execute_query(db, body.sql)

    # Track run if this was a saved query
    if body.saved_query_id:
        try:
            record_query_run(db, body.saved_query_id)
            db.commit()
        except Exception:
            db.rollback()

    return result


@router.get("/saved")  # noqa: API001
async def get_saved_queries(
    ctx: UserContext = Depends(get_current_super_admin_api),
    db: Session = Depends(get_db),
):
    """List all saved queries."""
    queries = list_saved_queries(db)
    return [
        {
            "id": q.id,
            "name": q.name,
            "description": q.description,
            "sql_text": q.sql_text,
            "created_by": q.created_by,
            "last_run_at": q.last_run_at.isoformat() if q.last_run_at else None,
            "run_count": q.run_count,
            "created_at": q.created_at.isoformat() if q.created_at else None,
        }
        for q in queries
    ]


@router.post("/saved")  # noqa: API001
async def create_saved(
    body: SavedQueryCreate,
    ctx: UserContext = Depends(get_current_super_admin_api),
    db: Session = Depends(get_db),
):
    """Create a new saved query."""
    q = create_saved_query(
        db,
        name=body.name,
        sql_text=body.sql_text,
        description=body.description,
        created_by=ctx.id,
    )
    db.commit()
    return {
        "id": q.id,
        "name": q.name,
        "description": q.description,
        "sql_text": q.sql_text,
        "created_by": q.created_by,
        "run_count": q.run_count,
        "created_at": q.created_at.isoformat() if q.created_at else None,
    }


@router.put("/saved/{query_id}")  # noqa: API001
async def update_saved(
    query_id: int,
    body: SavedQueryUpdate,
    ctx: UserContext = Depends(get_current_super_admin_api),
    db: Session = Depends(get_db),
):
    """Update a saved query."""
    q = update_saved_query(
        db,
        query_id,
        name=body.name,
        sql_text=body.sql_text,
        description=body.description,
    )
    db.commit()
    return {
        "id": q.id,
        "name": q.name,
        "description": q.description,
        "sql_text": q.sql_text,
        "run_count": q.run_count,
    }


@router.delete("/saved/{query_id}")  # noqa: API001
async def delete_saved(
    query_id: int,
    ctx: UserContext = Depends(get_current_super_admin_api),
    db: Session = Depends(get_db),
):
    """Delete a saved query."""
    delete_saved_query(db, query_id)
    db.commit()
    return {"ok": True}
