import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';
import { withEdgeRetry, isRetryableError, isDeadlockError } from '../_shared/retryHelper.ts';
import { corsHeadersWithMethods } from '../_shared/cors.ts';

export default createEdgeFunction(
  {
    name: 'backfill-company-data',
    requireAuth: true,
    corsHeaders: corsHeadersWithMethods,
  },
  async (req, context, supabase) => {
    edgeLogger.info('Starting company data backfill', { requestId: context.requestId });

    // Check if user is superuser
    const { data: profile, error: profileError } = await supabase
      .from('user_profiles')
      .select('role')
      .eq('id', context.user.id)
      .single();

    if (profileError || profile?.role !== 'superuser') {
      edgeLogger.warn('Unauthorized backfill attempt', {
        userId: context.user.id,
        requestId: context.requestId
      });
      return new Response(
        JSON.stringify({ error: 'Unauthorized: Superuser access required' }),
        { status: 403, headers: { ...corsHeadersWithMethods, 'Content-Type': 'application/json' } }
      );
    }

    // Execute the backfill function with retry logic
    const { data, error } = await withEdgeRetry(
      async () => {
        const result = await supabase.rpc('backfill_company_data');
        if (result.error) throw result.error;
        return result;
      },
      {
        maxAttempts: 5,
        baseDelay: 2000,
        maxDelay: 30000,
        backoffMultiplier: 2,
        jitter: true,
        shouldRetry: (error) => isRetryableError(error) || isDeadlockError(error)
      },
      context.requestId,
      'backfill_company_data'
    );

    edgeLogger.info('Company data backfill completed', {
      results: data,
      requestId: context.requestId
    });

    return new Response(
      JSON.stringify({
        success: true,
        ...data,
      }),
      { headers: { ...corsHeadersWithMethods, 'Content-Type': 'application/json' } }
    );
  }
);
