/**
 * Custom Content Retry Edge Function
 *
 * Manually retry processing for stuck content
 *
 * POST /custom-content-retry
 * Body: { content_id, store_id }
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

Deno.serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    // Get Supabase client
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseServiceKey);

    // Verify authentication
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) {
      return new Response(
        JSON.stringify({ error: 'Missing authorization header' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const token = authHeader.replace('Bearer ', '');
    const { data: { user }, error: authError } = await supabase.auth.getUser(token);

    if (authError || !user) {
      return new Response(
        JSON.stringify({ error: 'Unauthorized' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Parse request body
    const { content_id, store_id } = await req.json();

    if (!content_id || !store_id) {
      return new Response(
        JSON.stringify({ error: 'Missing required fields: content_id, store_id' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Verify user owns this content
    const { data: content, error: contentError } = await supabase
      .from('custom_content')
      .select('id, user_id, sync_status')
      .eq('id', content_id)
      .eq('store_id', store_id)
      .eq('user_id', user.id)
      .single();

    if (contentError || !content) {
      return new Response(
        JSON.stringify({ error: 'Content not found or access denied' }),
        { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    console.log(`[Retry] Retrying processing for content ${content_id}`);

    // Reset status to pending
    await supabase
      .from('custom_content')
      .update({
        sync_status: 'pending',
        sync_started_at: null,
        sync_completed_at: null,
        sync_error: null,
      })
      .eq('id', content_id);

    // Trigger processing
    const processUrl = `${supabaseUrl}/functions/v1/custom-content-process`;
    const processResponse = await fetch(processUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${supabaseServiceKey}`,
      },
      body: JSON.stringify({
        content_id: content_id,
        store_id: store_id,
      }),
    });

    if (!processResponse.ok) {
      const errorText = await processResponse.text();
      console.error('[Retry] Processing trigger failed:', errorText);
      throw new Error(`Failed to trigger processing: ${errorText}`);
    }

    return new Response(
      JSON.stringify({
        success: true,
        message: 'Processing retry initiated',
        contentId: content_id,
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

  } catch (error: any) {
    console.error('[Retry] Error:', error);
    return new Response(
      JSON.stringify({
        error: error.message || 'Internal server error',
        details: error.toString(),
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
