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

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await requireAdopsAccess();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { id } = await params;
  const supabase = await createClient();
  const body = await request.json();

  const updates: Record<string, any> = { flight_status: body.flight_status, updated_at: new Date().toISOString() };
  if (body.flight_status === 'active' && body.reactivation_reason) {
    updates.reactivated_at = new Date().toISOString();
    updates.reactivation_reason = body.reactivation_reason;
  }

  const { error } = await supabase.from('rmp_io_extensions').update(updates).eq('id', id);
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

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