/**
 * GET /api/phishing/campaigns
 *   Returns a paginated list of phishing campaigns.
 *   Query params:
 *     limit  (default 50, max 200)
 *     offset (default 0)
 *     status (optional filter, e.g. 'open')
 */

import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';

interface CampaignRow {
  id: string;
  campaign_key: string | null;
  group_method: string | null;
  first_seen_at: string | null;
  last_seen_at: string | null;
  report_count: number;
  status: string;
  created_at: string;
  first_report_ticket_id: string | null;
}

export async function GET(request: NextRequest) {
  const { error } = await requirePermission('phishing', 'read');
  if (error) return error;

  try {
    const url = request.nextUrl;
    const rawLimit = parseInt(url.searchParams.get('limit') ?? '50', 10);
    const limit = Math.min(Math.max(Number.isFinite(rawLimit) ? rawLimit : 50, 0), 200);
    const offset = Math.max(parseInt(url.searchParams.get('offset') ?? '0', 10) || 0, 0);
    const status = url.searchParams.get('status');

    const params: unknown[] = [limit, offset];
    let statusFilter = '';
    if (status) {
      params.push(status);
      statusFilter = `WHERE c.status = $${params.length}`;
    }

    const campaigns = await postgresClient.query<CampaignRow>(
      `SELECT c.id::text, c.campaign_key, c.group_method, c.first_seen_at::text, c.last_seen_at::text,
              c.report_count, c.status, c.created_at::text,
              (SELECT r.ticket_id::text FROM reports r WHERE r.campaign_id = c.id ORDER BY r.created_at ASC LIMIT 1) AS first_report_ticket_id
         FROM campaigns c
         ${statusFilter}
        ORDER BY c.last_seen_at DESC NULLS LAST
        LIMIT $1 OFFSET $2`,
      params
    );

    const countParams: unknown[] = [];
    let countFilter = '';
    if (status) {
      countParams.push(status);
      countFilter = `WHERE status = $${countParams.length}`;
    }

    const totalRes = await postgresClient.query<{ count: string }>(
      `SELECT COUNT(*)::text AS count FROM campaigns ${countFilter}`,
      countParams
    );
    const total = parseInt(totalRes.rows[0]?.count ?? '0', 10);

    const items = campaigns.rows.map((c) => ({
      id: c.id,
      campaignKey: c.campaign_key,
      groupMethod: c.group_method,
      firstSeenAt: c.first_seen_at,
      lastSeenAt: c.last_seen_at,
      reportCount: c.report_count,
      status: c.status,
      createdAt: c.created_at,
      firstReportTicketId: c.first_report_ticket_id,
    }));

    return NextResponse.json({ items, total, limit, offset });
  } catch (err) {
    console.error('[PHISHING-CAMPAIGNS] Failed to list campaigns', err);
    return NextResponse.json(
      { error: 'Failed to list campaigns', message: err instanceof Error ? err.message : 'Unknown error' },
      { status: 500 }
    );
  }
}
