import type { APIRoute } from 'astro';
import { createSupabaseServerClient } from '../../../lib/supabase-ssr';

export const GET: APIRoute = async ({ cookies }) => {
  try {
    const supabase = createSupabaseServerClient(cookies);
    const { data: { session }, error: sessionError } = await supabase.auth.getSession();

    if (sessionError || !session) {
      return new Response(JSON.stringify({
        authenticated: false,
        isAdmin: false,
        error: 'No active session'
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if user is admin
    const { data: userRecord, error: userError } = await supabase
      .from('users')
      .select('role, organization_id')
      .eq('id', session.user.id)
      .single();

    if (userError) {
      console.error('Admin auth check user lookup error:', userError);
      return new Response(JSON.stringify({
        authenticated: true,
        isAdmin: false,
        error: 'User lookup failed'
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const isAdmin = userRecord?.role === 'admin';

    return new Response(JSON.stringify({
      authenticated: true,
      isAdmin,
      user: {
        id: session.user.id,
        email: session.user.email,
        name: userRecord?.name || session.user.user_metadata?.name || session.user.email
      },
      organizationId: userRecord?.organization_id
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Admin auth check error:', error);
    return new Response(JSON.stringify({
      authenticated: false,
      isAdmin: false,
      error: 'Authentication check failed'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};