import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

Deno.serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    // Create admin client
    const supabaseAdmin = createClient(
      Deno.env.get('SUPABASE_URL')!,
      Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
      {
        auth: {
          autoRefreshToken: false,
          persistSession: false
        }
      }
    );

    const now = new Date().toISOString();

    // Find expired bans
    const { data: expiredBans, error: fetchError } = await supabaseAdmin
      .from('profiles')
      .select('user_id, username, ban_reason, ban_expires_at')
      .eq('banned', true)
      .not('ban_expires_at', 'is', null)
      .lte('ban_expires_at', now);

    if (fetchError) {
      console.error('Error fetching expired bans:', fetchError);
      throw fetchError;
    }

    console.log(`Found ${expiredBans?.length || 0} expired bans to process`);

    // Unban users with expired bans
    const unbannedUsers: string[] = [];
    for (const profile of expiredBans || []) {
      console.log(`Unbanning user: ${profile.username} (${profile.user_id})`);
      
      const { error: unbanError } = await supabaseAdmin
        .from('profiles')
        .update({ 
          banned: false, 
          ban_reason: null,
          ban_expires_at: null 
        })
        .eq('user_id', profile.user_id);

      if (unbanError) {
        console.error(`Failed to unban ${profile.username}:`, unbanError);
        continue;
      }

      // Log the automatic unban
      const { error: logError } = await supabaseAdmin
        .rpc('log_admin_action', {
          _admin_user_id: '00000000-0000-0000-0000-000000000000', // System user ID
          _target_user_id: profile.user_id,
          _action: 'auto_unban',
          _details: { 
            reason: 'Ban expired',
            original_ban_reason: profile.ban_reason,
            expired_at: profile.ban_expires_at 
          }
        });

      if (logError) {
        console.error(`Failed to log auto-unban for ${profile.username}:`, logError);
      }

      unbannedUsers.push(profile.username);
    }

    console.log(`Successfully unbanned ${unbannedUsers.length} users`);

    return new Response(
      JSON.stringify({ 
        success: true,
        unbanned_count: unbannedUsers.length,
        unbanned_users: unbannedUsers,
        processed_at: now
      }),
      { 
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        status: 200 
      }
    );

  } catch (error) {
    console.error('Error in process-expired-bans:', error);
    return new Response(
      JSON.stringify({ 
        error: error instanceof Error ? error.message : 'Unknown error',
        success: false 
      }),
      { 
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        status: 500 
      }
    );
  }
});
