import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { corsHeaders } from '../_shared/cors.ts';

const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
  addSpanEvent(span, 'processing_expired_bans', { requestId });

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

    // Find expired bans
    const { data: expiredBans, error: fetchError } = await supabase
      .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) {
      addSpanEvent(span, 'error_fetching_expired_bans', { error: fetchError.message });
      throw fetchError;
    }

    addSpanEvent(span, 'found_expired_bans', { count: expiredBans?.length || 0 });

    // Unban users with expired bans
    const unbannedUsers: string[] = [];
    for (const profile of expiredBans || []) {
      addSpanEvent(span, 'unbanning_user', { 
        username: profile.username,
        userId: profile.user_id
      });
      
      const { error: unbanError } = await supabase
        .from('profiles')
        .update({ 
          banned: false, 
          ban_reason: null,
          ban_expires_at: null 
        })
        .eq('user_id', profile.user_id);

      if (unbanError) {
        addSpanEvent(span, 'failed_to_unban_user', { 
          username: profile.username,
          error: unbanError.message
        });
        continue;
      }

      // Log the automatic unban
      const { error: logError } = await supabase
        .rpc('log_admin_action', {
          _admin_user_id: '00000000-0000-0000-0000-000000000000',
          _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) {
        addSpanEvent(span, 'failed_to_log_auto_unban', { 
          username: profile.username,
          error: logError.message
        });
      }

      unbannedUsers.push(profile.username);
    }

    addSpanEvent(span, 'successfully_unbanned_users', { count: unbannedUsers.length });

    return { 
      success: true,
      unbanned_count: unbannedUsers.length,
      unbanned_users: unbannedUsers,
      processed_at: now
    };
};

serve(createEdgeFunction({
  name: 'process-expired-bans',
  requireAuth: false,
  corsHeaders,
  enableTracing: true,
}, handler));
