from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session

from app.core.response import error, ok
from app.db.models import User
from app.db.session import get_db
from app.deps import require_staff
from app.schemas.models import ReportReviewRequest
from app.services import admin as admin_service
from app.services import report_review as review_service
from app.services.reports import report_to_dict

router = APIRouter(prefix="/api/admin", tags=["Admin"])


@router.get("/dashboard")
def admin_dashboard(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_staff),
):
    metrics = admin_service.get_dashboard_metrics(db, tenant_id=current_user.tenant_id)
    return ok(metrics, request_id=request.state.request_id)


@router.get("/reports/pending")
def pending_reports(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_staff),
):
    items = review_service.list_pending_reports(db, tenant_id=current_user.tenant_id)
    return ok({"list": items}, request_id=request.state.request_id)


@router.post("/reports/{report_id}/review")
def review_report(
    report_id: int,
    body: ReportReviewRequest,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_staff),
):
    report, err = review_service.review_report(
        db,
        current_user.id,
        report_id,
        body.action,
        tenant_id=current_user.tenant_id,
        note=body.note,
    )
    if err == "report_not_found":
        return JSONResponse(
            status_code=404,
            content=error(10008, "report_not_found", request.state.request_id),
        )
    if err == "invalid_status":
        return JSONResponse(
            status_code=409,
            content=error(10012, "invalid_report_status", request.state.request_id),
        )
    if err == "invalid_action":
        return JSONResponse(
            status_code=400,
            content=error(10013, "invalid_review_action", request.state.request_id),
        )
    return ok(report_to_dict(report), message="reviewed", request_id=request.state.request_id)
