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

export default createEdgeFunction(
  {
    name: 'cancel-email-change',
    requireAuth: true,
    corsHeaders: corsHeaders
  },
  async (req, context) => {
    context.span.setAttribute('action', 'cancel_email_change');
    edgeLogger.info('Cancelling email change for user', { 
      action: 'cancel_email_change',
      requestId: context.requestId,
      userId: context.userId 
    });

    // SECURITY: Service Role Key Usage
    // ---------------------------------
    // This function uses the service role key to bypass RLS and access auth.users table.
    // This is required because:
    // 1. The cancel_user_email_change() database function has SECURITY DEFINER privileges
    // 2. It needs to modify auth.users table which is not accessible with regular user tokens
    // 3. User authentication is verified via the wrapper's requireAuth
    // Scope: Limited to cancelling the authenticated user's own email change
    const supabaseUrl = Deno.env.get('SUPABASE_URL');
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
    
    if (!supabaseUrl || !supabaseServiceKey) {
      throw new Error('Missing Supabase configuration');
    }

    const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey, {
      auth: {
        autoRefreshToken: false,
        persistSession: false
      }
    });

    // Call the database function to clear email change fields
    // This function has SECURITY DEFINER privileges to access auth.users
    const { data: cancelled, error: cancelError } = await supabaseAdmin
      .rpc('cancel_user_email_change', { _user_id: context.userId });

    if (cancelError || !cancelled) {
      edgeLogger.error('Error cancelling email change', { 
        error: cancelError?.message, 
        userId: context.userId, 
        requestId: context.requestId 
      });
      throw new Error('Unable to cancel email change: ' + (cancelError?.message || 'Unknown error'));
    }

    edgeLogger.info('Successfully cancelled email change', { userId: context.userId, requestId: context.requestId });

    // Log the cancellation in admin_audit_log
    const { error: auditError } = await supabaseAdmin
      .from('admin_audit_log')
      .insert({
        admin_user_id: context.userId,
        target_user_id: context.userId,
        action: 'email_change_cancelled',
        details: {
          cancelled_at: new Date().toISOString(),
        },
      });

    if (auditError) {
      edgeLogger.error('Error logging audit', { 
        error: auditError.message, 
        requestId: context.requestId 
      });
      // Don't fail the request if audit logging fails
    }

    edgeLogger.info('Successfully cancelled email change', { 
      action: 'cancel_email_change',
      requestId: context.requestId,
      userId: context.userId
    });

    return new Response(
      JSON.stringify({
        success: true,
        message: 'Email change cancelled successfully',
        user: {
          id: context.userId,
          email: null,
          new_email: null,
        },
      }),
      {
        headers: { 
          'Content-Type': 'application/json'
        },
        status: 200,
      }
    );
  }
);
