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

// Simple rate limiting for session endpoint
const sessionChecks = new Map<string, { count: number; lastReset: number }>();
const RATE_LIMIT_WINDOW = 60000; // 1 minute
const MAX_REQUESTS = 30; // Max 30 requests per minute per IP (increased from 10)

function checkRateLimit(clientIP: string): boolean {
  const now = Date.now();
  const windowStart = now - RATE_LIMIT_WINDOW;
  
  let entry = sessionChecks.get(clientIP);
  
  if (!entry || entry.lastReset < windowStart) {
    entry = { count: 0, lastReset: now };
    sessionChecks.set(clientIP, entry);
  }
  
  entry.count++;
  
  return entry.count <= MAX_REQUESTS;
}

export const GET: APIRoute = async ({ request, cookies }) => {
  // Get client IP for rate limiting
  const clientIP = request.headers.get('x-forwarded-for') || 
                   request.headers.get('x-real-ip') || 
                   'unknown';
  
  // Check rate limit
  if (!checkRateLimit(clientIP)) {
    console.warn('[SESSION] Rate limit exceeded for IP:', clientIP);
    return new Response(JSON.stringify({
      authenticated: false,
      error: 'Rate limit exceeded. Please try again later.'
    }), {
      status: 429,
      headers: { 'Content-Type': 'application/json' }
    });
  }
  
  const supabase = createSupabaseServerClient(cookies);
  
  console.log('[SESSION] Checking session...');
  const { data: { session }, error } = await supabase.auth.getSession();
  
  console.log('[SESSION] Session check result:', {
    hasSession: !!session,
    error: error?.message,
    userId: session?.user?.id
  });

  if (error || !session) {
    console.log('[SESSION] Session validation failed:', error?.message || 'No session found');
    return new Response(JSON.stringify({
      authenticated: false,
      error: error?.message || 'No active session'
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  }
  
  // Get user details with proper error handling
  const { data: userRecord, error: userError } = await supabase
    .from('users')
    .select('role, organization_id')
    .eq('id', session.user.id)
    .single();

  if (userError) {
    console.error('[SESSION] User lookup failed:', userError);
    return new Response(JSON.stringify({
      authenticated: true, // Still authenticated even if user details fail
      user: session.user,
      isAdmin: false,
      isSuperAdmin: false,
      organizationId: null
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  }
  
  return new Response(JSON.stringify({
    authenticated: true,
    user: session.user,
    isAdmin: userRecord.role === 'admin',
    isSuperAdmin: false, // Removed until proper column exists
    organizationId: userRecord.organization_id
  }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
};