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 { id, tenantId } = await req.json();
    if (!id || !tenantId) {
      return NextResponse.json({ error: 'id and tenantId are required' }, { status: 400 });
    }

    const r = await postgresClient.query(
      `SELECT * FROM mimecast_tenants WHERE id = $1 AND 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.releaseHeldMessage(id);

    if (!result.released) {
      return NextResponse.json({ error: result.error ?? 'Release failed — message may already be released or expired' }, { status: 422 });
    }

    return NextResponse.json({ released: true });
  } catch (error: any) {
    console.error('[HeldMail] release error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
