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

export async function GET() {
  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);

    // Fetch auth users
    const { data: authData, error: authErr } = await supabaseAdmin.auth.admin.listUsers();
    if (authErr) throw authErr;

    // Fetch profiles
    const { data: profilesData, error: profErr } = await supabaseAdmin.from('profiles').select('*');
    if (profErr) throw profErr;

    // Merge them
    const users = (authData.users || []).map(authUser => {
      const profile = profilesData.find(p => p.id === authUser.id) || {};
      return {
        id: authUser.id,
        email: authUser.email,
        full_name: profile.full_name || 'N/A',
        role: profile.role || 'public',
        password_changed: profile.password_changed,
        created_at: authUser.created_at
      };
    });

    return NextResponse.json({ users });
  } catch (error) {
    console.error('Users API GET Error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function POST(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);
    const body = await request.json();
    const { email, password, full_name, role, hub_id } = body;

    if (!email || !password || !full_name || !role) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    // 1. Create user in Auth
    const { data: authData, error: authErr } = await supabaseAdmin.auth.admin.createUser({
      email,
      password,
      email_confirm: true, // Auto-confirm email
    });

    if (authErr) throw authErr;

    const newUserId = authData.user.id;

    // 2. Insert into profiles (bypassing RLS with service role)
    const { error: profErr } = await supabaseAdmin.from('profiles').insert([{
      id: newUserId,
      full_name,
      role,
      password_changed: false // Force change password on first login
    }]);

    // If profile insert fails, we rollback the auth user creation
    if (profErr) {
      await supabaseAdmin.auth.admin.deleteUser(newUserId);
      throw profErr;
    }

    // 3. Assign user to worship hub (if role is pic or hub_head and hub_id is provided)
    if (hub_id && (role === 'pic' || role === 'hub_head')) {
      const updateData = {};
      if (role === 'pic') {
        updateData.pic_id = newUserId;
      } else if (role === 'hub_head') {
        updateData.head_id = newUserId;
      }

      const { error: hubErr } = await supabaseAdmin
        .from('hubs')
        .update(updateData)
        .eq('id', hub_id);

      if (hubErr) {
        // Rollback profile and auth user
        await supabaseAdmin.from('profiles').delete().eq('id', newUserId);
        await supabaseAdmin.auth.admin.deleteUser(newUserId);
        throw hubErr;
      }
    }

    return NextResponse.json({ success: true, user: authData.user });
  } catch (error) {
    console.error('Users API POST Error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

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);
    
    // Using searchParams to get ID
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');

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

    // Delete from auth.users (Cascades to profiles table via foreign key)
    const { error } = await supabaseAdmin.auth.admin.deleteUser(id);

    if (error) throw error;

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