import { NextRequest, NextResponse } from 'next/server';
import { postgresClient as pg } from '@/lib/services/postgres-client';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const days = parseInt(searchParams.get('days') ?? '7');
    const limit = Math.min(parseInt(searchParams.get('limit') ?? '200'), 1000);
    const search = searchParams.get('search') ?? '';
    const direction = searchParams.get('direction') ?? '';
    const status = searchParams.get('status') ?? '';

    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - days);

    const conditions: string[] = ['sent_datetime >= $1'];
    const params: any[] = [cutoff.toISOString()];
    let paramIdx = 2;

    if (direction) {
      conditions.push(`direction = $${paramIdx++}`);
      params.push(direction);
    }
    if (status) {
      conditions.push(`status = $${paramIdx++}`);
      params.push(status);
    }
    if (search) {
      conditions.push(`(
        sender_address ILIKE $${paramIdx} OR
        recipient_address ILIKE $${paramIdx} OR
        subject ILIKE $${paramIdx}
      )`);
      params.push(`%${search}%`);
      paramIdx++;
    }

    const where = conditions.join(' AND ');
    params.push(limit);

    const result = await pg.query(`
      SELECT id, sender_address, sender_domain, recipient_address, subject,
             direction, status, action, spam_score, size_bytes, attachment_count,
             sent_datetime, received_datetime, route, reject_reason, held_reason, source_ip
      FROM mimecast_messages
      WHERE ${where}
      ORDER BY sent_datetime DESC
      LIMIT $${paramIdx}
    `, params);

    return NextResponse.json({ messages: result.rows });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
