import { createClient } from '@supabase/supabase-js';
import { NextResponse } from 'next/server';

export async function DELETE(request) {
  try {
    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
    const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

    if (!supabaseServiceKey) {
      return NextResponse.json({ error: 'Service role key not configured' }, { status: 500 });
    }

    const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey);
    
    // Get Hub ID
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');

    if (!id) {
      return NextResponse.json({ error: 'Missing hub id' }, { status: 400 });
    }

    // 1. Fetch Hub to identify connected users (pic_id & head_id)
    const { data: hub, error: fetchErr } = await supabaseAdmin
      .from('hubs')
      .select('pic_id, head_id')
      .eq('id', id)
      .single();

    if (fetchErr) {
      console.error(`Failed to fetch hub ${id}:`, fetchErr);
      return NextResponse.json({ error: 'Hub not found' }, { status: 404 });
    }

    // 2. Delete connected accounts if they exist
    if (hub.pic_id) {
      try {
        const { error: delPicErr } = await supabaseAdmin.auth.admin.deleteUser(hub.pic_id);
        if (delPicErr) console.error(`Error deleting PIC user ${hub.pic_id} from Auth:`, delPicErr);
      } catch (err) {
        console.error(`Failed to delete PIC user ${hub.pic_id}:`, err);
      }
    }

    if (hub.head_id) {
      try {
        const { error: delHeadErr } = await supabaseAdmin.auth.admin.deleteUser(hub.head_id);
        if (delHeadErr) console.error(`Error deleting Head user ${hub.head_id} from Auth:`, delHeadErr);
      } catch (err) {
        console.error(`Failed to delete Head user ${hub.head_id}:`, err);
      }
    }

    // 3. Delete the Hub (cascades donations, sets household assignments to NULL)
    const { error: deleteErr } = await supabaseAdmin
      .from('hubs')
      .delete()
      .eq('id', id);

    if (deleteErr) throw deleteErr;

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Hubs API DELETE Error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
