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

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

    // Run system maintenance (orphaned image cleanup)
    const { data: maintenanceData, error: maintenanceError } = await supabase.rpc('run_system_maintenance');
    
    if (maintenanceError) {
      edgeLogger.error('Maintenance failed', { 
        error: maintenanceError.message,
        requestId: context.requestId 
      });
    } else {
      edgeLogger.info('Maintenance completed', { 
        result: maintenanceData,
        requestId: context.requestId 
      });
    }

    // Run pipeline monitoring checks
    const { data: monitoringData, error: monitoringError } = await supabase.rpc('run_pipeline_monitoring');
    
    if (monitoringError) {
      edgeLogger.error('Pipeline monitoring failed', { 
        error: monitoringError.message,
        requestId: context.requestId 
      });
    } else {
      edgeLogger.info('Pipeline monitoring completed', { 
        result: monitoringData,
        requestId: context.requestId 
      });
    }

    return new Response(
      JSON.stringify({ 
        success: true, 
        maintenance: maintenanceData,
        monitoring: monitoringData,
      }), 
      { headers: { 'Content-Type': 'application/json' } }
    );
  }
);
