from fastapi import APIRouter, Depends, HTTPException, Query
from typing import List, Optional
import db
import auth_utils
from dependencies import require_admin

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

@router.get("/audit-logs")
async def get_audit_logs(
    page: int = Query(1, ge=1),
    size: int = Query(50, ge=1, le=100),
    action: Optional[str] = None,
    admin: dict = Depends(require_admin)
):
    
    offset = (page - 1) * size
    
    query = """
        SELECT a.*, u.email as user_email,
               u2.email as target_user_email,
               o.first_name as target_order_name
        FROM audit_logs a
        LEFT JOIN users u ON a.user_id = u.id
        LEFT JOIN users u2 ON (a.target_type = 'user' AND a.target_id = u2.id)
        LEFT JOIN orders o ON (a.target_type = 'order' AND a.target_id = o.id)
    """
    params = []
    
    if action:
        query += " WHERE a.action = %s"
        params.append(action)
    
    query += " ORDER BY a.created_at DESC LIMIT %s OFFSET %s"
    params.extend([size, offset])
    
    logs = db.execute_query(query, tuple(params))
    
    # Total count for pagination
    count_query = "SELECT COUNT(*) as total FROM audit_logs"
    if action:
        count_query += " WHERE action = %s"
        total = db.execute_query(count_query, (action,))
    else:
        total = db.execute_query(count_query)
        
    return {
        "logs": logs,
        "total": total[0]['total'],
        "page": page,
        "size": size
    }

@router.get("/reviews")
async def get_admin_reviews(
    page: int = Query(1, ge=1),
    size: int = Query(50, ge=1, le=100),
    admin: dict = Depends(require_admin)
):
    offset = (page - 1) * size
    query = """
    SELECT id, first_name, last_name, email, rating, review_text, review_approved, created_at
    FROM orders 
    WHERE review_text IS NOT NULL AND review_text != ''
    ORDER BY created_at DESC
    LIMIT %s OFFSET %s
    """
    results = db.execute_query(query, (size, offset))
    
    count_res = db.execute_query("SELECT COUNT(*) as total FROM orders WHERE review_text IS NOT NULL AND review_text != ''")
    results_total = count_res[0]['total'] if count_res else 0
    
    return {"reviews": results, "total": results_total}
