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

export const POST: APIRoute = async ({ request, cookies }) => {
  try {
    const { email } = await request.json();
    
    if (!email) {
      return new Response(JSON.stringify({ 
        error: 'Email is required' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const supabase = createSupabaseServerClient(cookies);
    
    // Get user by email from auth.users
    const { data: authUsers, error: authError } = await supabase.auth.admin.listUsers();
    const authUser = authUsers?.users?.find(user => user.email === email);
    
    if (!authUser) {
      return new Response(JSON.stringify({
        success: true,
        found: false,
        message: 'User not found in auth.users table'
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Get user from users table
    const { data: userData, error: userError } = await supabase
      .from('users')
      .select('id, email, organization_id, role, created_at')
      .eq('id', authUser.id)
      .single();
    
    // Get organization data if user has one
    let organizationData = null;
    if (userData?.organization_id) {
      const { data: orgData, error: orgError } = await supabase
        .from('organizations')
        .select('id, name, stripe_account_id, created_at')
        .eq('id', userData.organization_id)
        .single();
      
      organizationData = { data: orgData, error: orgError?.message };
    }
    
    return new Response(JSON.stringify({
      success: true,
      found: true,
      authUser: {
        id: authUser.id,
        email: authUser.email,
        created_at: authUser.created_at,
        confirmed_at: authUser.confirmed_at
      },
      userData: {
        data: userData,
        error: userError?.message
      },
      organizationData,
      diagnostic: {
        hasUserRecord: !!userData,
        hasOrganization: !!userData?.organization_id,
        isAdmin: userData?.role === 'admin',
        shouldRedirectToOnboarding: !userData?.organization_id
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('User status debug error:', error);
    return new Response(JSON.stringify({ 
      error: 'An error occurred while checking user status',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};