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

export default createEdgeFunction(
  {
    name: 'data-retention-cleanup',
    requireAuth: false,
  },
  async (req, context, supabase) => {
    edgeLogger.info('Starting data retention cleanup', { requestId: context.requestId });

    // Call the master cleanup function
    const { data, error } = await supabase.rpc('run_data_retention_cleanup');

    if (error) {
      edgeLogger.error('Error running data retention cleanup', { 
        error,
        requestId: context.requestId 
      });
      throw error;
    }

    edgeLogger.info('Data retention cleanup completed', { 
      results: data,
      requestId: context.requestId 
    });

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