import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';

// GET /api/adops/cron/rmp-renewal-warnings — run daily 9:00 AM
export async function GET(request: NextRequest) {
  const secret = request.headers.get('x-cron-secret') ?? request.nextUrl.searchParams.get('secret');
  if (secret !== process.env.CRON_SECRET) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const supabase = await createClient();
  const in30 = new Date(Date.now() + 30 * 86400000).toISOString().split('T')[0];

  const { data: expiring } = await supabase
    .from('rmp_io_extensions')
    .select('id, client_id, staff_id, rmp_clients(company_name), rmp_sales_staff(email, full_name)')
    .in('flight_status', ['active', 'scheduled'])
    .eq('end_date', in30)
    .eq('renewal_notice_sent', false);

  let count = 0;
  for (const io of (expiring ?? [])) {
    await supabase.from('rmp_io_extensions').update({ renewal_notice_sent: true, renewal_notice_sent_at: new Date().toISOString() }).eq('id', io.id);

    const staffEmail = (io as any).rmp_sales_staff?.email;
    const staffName = (io as any).rmp_sales_staff?.full_name ?? 'Salesperson';
    const clientName = (io as any).rmp_clients?.company_name ?? 'Unknown';

    await supabase.from('rmp_adops_notifications').insert([
      {
        io_extension_id: io.id,
        notification_type: 'renewal_warning',
        recipient_type: 'admin',
        recipient_email: process.env.NOTIFY_EMAIL,
        message: `Renewal warning: IO for ${clientName} expires in 30 days`,
        sent_via: 'email',
        success: true,
      },
      ...(staffEmail ? [{
        io_extension_id: io.id,
        notification_type: 'renewal_warning',
        recipient_type: 'salesperson',
        recipient_email: staffEmail,
        message: `Your IO for ${clientName} expires in 30 days — time to renew`,
        sent_via: 'email',
        success: true,
      }] : []),
    ]);

    count++;
  }

  return NextResponse.json({ ok: true, warned: count });
}
