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

export async function checkUserBanned(
  userId: string,
  supabase: SupabaseClient
): Promise<{ banned: boolean; ban_reason?: string; error?: string }> {
  try {
    const { data: profile, error } = await supabase
      .from('profiles')
      .select('banned, ban_reason')
      .eq('user_id', userId)
      .single();

    if (error) {
      edgeLogger.error('Ban check failed', { userId, error: error.message });
      return { banned: false, error: 'Unable to verify account status' };
    }

    if (!profile) {
      return { banned: false, error: 'Profile not found' };
    }

    return { 
      banned: profile.banned,
      ban_reason: profile.ban_reason || undefined
    };
  } catch (error) {
    edgeLogger.error('Ban check exception', { userId, error });
    return { banned: false, error: 'Internal error checking account status' };
  }
}

export function createBannedResponse(requestId: string, corsHeaders: Record<string, string>, ban_reason?: string) {
  const message = ban_reason 
    ? `Your account has been suspended. Reason: ${ban_reason}`
    : 'Your account has been suspended. Contact support for assistance.';
    
  return new Response(
    JSON.stringify({ 
      error: 'Account suspended',
      message,
      ban_reason,
      requestId
    }),
    { 
      status: 403, 
      headers: { 
        ...corsHeaders, 
        'Content-Type': 'application/json',
        'X-Request-ID': requestId 
      } 
    }
  );
}

export function createUnbannedResponse(requestId: string, corsHeaders: Record<string, string>) {
  return new Response(
    JSON.stringify({ 
      success: true,
      message: 'Account restored. You can now access the application.',
      requestId
    }),
    { 
      status: 200, 
      headers: { 
        ...corsHeaders, 
        'Content-Type': 'application/json',
        'X-Request-ID': requestId 
      } 
    }
  );
}
