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

export const POST: APIRoute = async ({ request, cookies }) => {
  try {
    const formData = await request.json();
    const { email, password } = formData;
    
    console.log('[LOGIN] Attempting login for:', email);
    
    if (!email || !password) {
      return new Response(JSON.stringify({ 
        error: 'Email and password are required' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const supabase = createSupabaseServerClient(cookies);
    console.log('[LOGIN] Created Supabase client');
    
    const { data, error } = await supabase.auth.signInWithPassword({
      email,
      password,
    });
    
    console.log('[LOGIN] Supabase response:', { 
      hasUser: !!data?.user, 
      hasSession: !!data?.session,
      error: error?.message 
    });
    
    if (error) {
      console.log('[LOGIN] Authentication failed:', error.message);
      return new Response(JSON.stringify({ 
        error: error.message 
      }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Get user organization
    console.log('[LOGIN] Looking up user data for ID:', data.user.id);
    const { data: userData, error: userError } = await supabase
      .from('users')
      .select('organization_id, role')
      .eq('id', data.user.id)
      .single();
    
    console.log('[LOGIN] User data lookup:', { 
      userData, 
      userError: userError?.message,
      hasOrganization: !!userData?.organization_id,
      userId: data.user.id
    });
    
    // If user lookup failed, log detailed error and return error response
    if (userError) {
      console.error('[LOGIN] User lookup failed:', {
        error: userError,
        userId: data.user.id,
        userEmail: data.user.email
      });
      return new Response(JSON.stringify({ 
        error: 'Failed to retrieve user profile. Please try again.' 
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const redirectTo = !userData?.organization_id 
      ? '/onboarding/organization' 
      : userData?.role === 'admin' 
        ? '/admin/dashboard' 
        : '/dashboard';
    
    console.log('[LOGIN] Redirecting to:', redirectTo);
    
    return new Response(JSON.stringify({
      success: true,
      user: data.user,
      organizationId: userData?.organization_id,
      isAdmin: userData?.role === 'admin',
      isSuperAdmin: false, // Super admin logic can be added later if needed
      redirectTo
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Login error:', error);
    return new Response(JSON.stringify({ 
      error: 'An error occurred during login' 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};