import { NextResponse } from 'next/server';
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies, headers } from 'next/headers';
import { detectDemoModeFromHeaders } from '@/lib/demo-detector';
import { DEMO_ORGANIZATION } from '@/lib/demo-data';

export async function GET() {
  // 🎭 Vérification du mode démo en premier
  const h = headers();
  const isDemoMode = detectDemoModeFromHeaders(h);
  
  if (isDemoMode) {
    console.log("🎭 [API ME/ROLE] Mode démo détecté - renvoi de données fictives");
    
    return NextResponse.json({
      is_staff: false,
      org_id: DEMO_ORGANIZATION.id
    });
  }

  try {
    const sb = createRouteHandlerClient({ cookies });
    const { data: { user } } = await sb.auth.getUser();
    if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 });

    // Is staff?
    let isStaff = false;
    try {
      const { data } = await sb.from('staff_users').select('is_staff').eq('user_id', user.id).maybeSingle();
      isStaff = !!data?.is_staff;
    } catch {}

    // Resolve active org id
    let org_id: string | null = null;
    if (isStaff) {
      org_id = cookies().get('active_org_id')?.value || null;
    } else {
      try {
        const { data } = await sb.rpc('get_my_org').maybeSingle();
        // rpc may return a plain object; coerce to any to access id safely
        const d: any = data;
        if (d?.id) org_id = String(d.id);
      } catch {}
    }

    if (!org_id) {
      return NextResponse.json({ role: null, isStaff, org_id: null });
    }

    // Read membership
    let role: string | null = null;
    try {
      const { data } = await sb
        .from('organization_members')
        .select('role, revoked')
        .eq('org_id', org_id)
        .eq('user_id', user.id)
        .maybeSingle();
      if (data && !data.revoked) role = String(data.role || '').toUpperCase();
    } catch {}

    // For staff with no membership, expose "STAFF"
    if (!role && isStaff) role = 'STAFF';

    return NextResponse.json({ role, isStaff, org_id });
  } catch (e: any) {
    return NextResponse.json({ error: e?.message || 'server_error' }, { status: 500 });
  }
}

