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


// GET /api/adops/cron/deactivate — run daily 11:59 PM
export async function GET(request: NextRequest) {
  // Verify cron secret
  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 today = new Date().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', today)
    .eq('auto_deactivate', true);

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

    // Log notification
    await supabase.from('rmp_adops_notifications').insert({
      io_extension_id: io.id,
      notification_type: 'flight_expired',
      recipient_type: 'admin',
      recipient_email: process.env.NOTIFY_EMAIL,
      message: `IO ${io.id} for ${(io as any).rmp_clients?.company_name ?? 'unknown'} expired today`,
      sent_via: 'email',
      success: true,
    });

    // Notify salesperson
    const staffEmail = (io as any).rmp_sales_staff?.email;
    if (staffEmail) {
      await supabase.from('rmp_adops_notifications').insert({
        io_extension_id: io.id,
        notification_type: 'flight_expired',
        recipient_type: 'salesperson',
        recipient_email: staffEmail,
        message: `Your IO for ${(io as any).rmp_clients?.company_name ?? 'unknown'} has expired`,
        sent_via: 'email',
        success: true,
      });
    }

    count++;
  }

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