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

export default createEdgeFunction(
  {
    name: 'backfill-park-locations',
    requireAuth: true,
    corsHeaders: corsHeadersWithMethods,
  },
  async (req, context, supabase) => {
    edgeLogger.info('Starting park location 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_park_locations');
        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_park_locations'
    );

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

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