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

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) {
      edgeLogger.error('Error fetching expired bans', { action: 'process_expired_bans', error: fetchError });
      throw fetchError;
    }

    edgeLogger.info(`Found ${expiredBans?.length || 0} expired bans to process`, { action: 'process_expired_bans', count: expiredBans?.length || 0 });

    // Unban users with expired bans
    const unbannedUsers: string[] = [];
    for (const profile of expiredBans || []) {
      edgeLogger.info('Unbanning user', { action: 'process_expired_bans', username: profile.username, userId: 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) {
        edgeLogger.error('Failed to unban user', { action: 'process_expired_bans', username: profile.username, error: 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) {
        edgeLogger.error('Failed to log auto-unban', { action: 'process_expired_bans', username: profile.username, error: logError });
      }

      unbannedUsers.push(profile.username);
    }

    edgeLogger.info('Successfully unbanned users', { action: 'process_expired_bans', count: unbannedUsers.length });

    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) {
    edgeLogger.error('Error in process-expired-bans', { action: '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 
      }
    );
  }
});
