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

export const dynamic = 'force-dynamic';

export async function POST(req: NextRequest) {
  try {
    const { tenantId, to, from, subject, startHours } = await req.json();

    if (!tenantId) {
      return NextResponse.json({ error: 'tenantId is required' }, { status: 400 });
    }
    if (!to && !from && !subject) {
      return NextResponse.json({ error: 'At least one of to, from, or subject is required' }, { status: 400 });
    }

    const r = await postgresClient.query(
      `SELECT mt.*, c.company_name FROM mimecast_tenants mt
       LEFT JOIN companies c ON c.id = mt.company_id
       WHERE mt.id = $1 AND mt.enabled = true`,
      [tenantId]
    );
    if (!r.rows.length) {
      return NextResponse.json({ error: 'Tenant not found' }, { status: 404 });
    }

    const client = getMimecastClientForTenant(r.rows[0]);
    const result = await client.searchDeliveredMessages({
      to: to || undefined,
      from: from || undefined,
      subject: subject || undefined,
      startHours: startHours ?? 24,
      route: 'INBOUND',
    });

    if (result.error) {
      return NextResponse.json({ error: result.error }, { status: 502 });
    }

    return NextResponse.json({ messages: result.messages, total: result.messages.length });
  } catch (error: any) {
    console.error('[Delivered] search error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
