/**
 * Compliance Logs API
 * View compliance logs and trigger manual report generation
 */

import { NextRequest, NextResponse } from 'next/server';
import { AuthMiddleware } from '@/lib/auth';
import { ComplianceService } from '@/lib/compliance';

/**
 * GET /api/admin/compliance
 * View compliance logs with optional filtering
 *
 * Query params:
 *   category - Filter by category (EMAIL, CONTENT, AGENT, SYSTEM, USER)
 *   days     - Number of days to look back (default: 7)
 *   limit    - Max results (default: 100)
 *   offset   - Pagination offset (default: 0)
 *   report   - If "true", returns aggregated daily report for today
 */
export async function GET(request: NextRequest) {
  try {
    const authResponse = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResponse) return authResponse;

    const searchParams = request.nextUrl.searchParams;
    const wantReport = searchParams.get('report') === 'true';

    if (wantReport) {
      const dateParam = searchParams.get('date');
      const date = dateParam ? new Date(dateParam) : undefined;
      const report = await ComplianceService.getDailyReport(date);
      return NextResponse.json({ report });
    }

    const category = searchParams.get('category') || undefined;
    const days = parseInt(searchParams.get('days') || '7');
    const limit = parseInt(searchParams.get('limit') || '100');
    const offset = parseInt(searchParams.get('offset') || '0');

    const { logs, total } = await ComplianceService.getLogs({ category, days, limit, offset });

    return NextResponse.json({ logs, total, limit, offset });
  } catch (error: any) {
    console.error('[ComplianceAPI] Error:', error);
    return NextResponse.json({ error: error.message || 'Internal error' }, { status: 500 });
  }
}

/**
 * POST /api/admin/compliance
 * Trigger a manual report generation and send
 *
 * Body: { date?: string } - optional date in YYYY-MM-DD format
 */
export async function POST(request: NextRequest) {
  try {
    const authResponse = await AuthMiddleware.requireRole(request, 'ADMIN');
    if (authResponse) return authResponse;

    const body = await request.json().catch(() => ({}));
    const date = body.date ? new Date(body.date) : undefined;

    const success = await ComplianceService.sendDailyReport(date);

    if (success) {
      return NextResponse.json({ success: true, message: 'Report sent to admin@eventheodds.ai' });
    } else {
      return NextResponse.json({ success: false, error: 'Failed to send report' }, { status: 500 });
    }
  } catch (error: any) {
    console.error('[ComplianceAPI] Error:', error);
    return NextResponse.json({ error: error.message || 'Internal error' }, { status: 500 });
  }
}
