import { NextRequest, NextResponse } from "next/server";
import { Pool } from "pg";
import { requireAdmin } from "@/lib/auth-utils";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

// GET /api/admin/audit-log - Get audit logs with pagination and filters
export async function GET(request: NextRequest) {
  const { error } = await requireAdmin();
  if (error) return error;

  try {
    const searchParams = request.nextUrl.searchParams;
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "50");
    const offset = (page - 1) * limit;
    
    const userId = searchParams.get("userId");
    const action = searchParams.get("action");
    const resource = searchParams.get("resource");
    const startDate = searchParams.get("startDate");
    const endDate = searchParams.get("endDate");

    let query = `
      SELECT 
        al.id, al.timestamp, al.user_id, al.user_email, al.action, 
        al.resource, al.resource_id, al.details, al.ip_address,
        u.name as user_name
      FROM "audit_log" al
      LEFT JOIN "user" u ON al.user_id = u.id
      WHERE 1=1
    `;
    const params: (string | number)[] = [];
    let paramIndex = 1;

    if (userId) {
      query += ` AND al.user_id = $${paramIndex++}`;
      params.push(userId);
    }

    if (action) {
      query += ` AND al.action = $${paramIndex++}`;
      params.push(action);
    }

    if (resource) {
      query += ` AND al.resource = $${paramIndex++}`;
      params.push(resource);
    }

    if (startDate) {
      query += ` AND al.timestamp >= $${paramIndex++}`;
      params.push(startDate);
    }

    if (endDate) {
      query += ` AND al.timestamp <= $${paramIndex++}`;
      params.push(endDate);
    }

    // Get total count
    const countQuery = query.replace(
      /SELECT[\s\S]*?FROM/,
      "SELECT COUNT(*) as total FROM"
    );
    const countResult = await pool.query(countQuery, params);
    const total = parseInt(countResult.rows[0].total);

    // Add pagination
    query += ` ORDER BY al.timestamp DESC LIMIT $${paramIndex++} OFFSET $${paramIndex}`;
    params.push(limit, offset);

    const result = await pool.query(query, params);

    // Get unique actions and resources for filters
    const actionsResult = await pool.query(
      'SELECT DISTINCT action FROM "audit_log" ORDER BY action'
    );
    const resourcesResult = await pool.query(
      'SELECT DISTINCT resource FROM "audit_log" ORDER BY resource'
    );

    return NextResponse.json({
      logs: result.rows,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
      filters: {
        actions: actionsResult.rows.map((r) => r.action),
        resources: resourcesResult.rows.map((r) => r.resource),
      },
    });
  } catch (error) {
    console.error("Error fetching audit logs:", error);
    return NextResponse.json(
      { error: "Failed to fetch audit logs" },
      { status: 500 }
    );
  }
}
