/**
 * Custom Content Sync Status Edge Function
 *
 * Returns the current sync status for a content entry
 * Used for polling during async processing
 *
 * GET /custom-content-sync-status?content_id={uuid}
 */

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 query parameter
    const url = new URL(req.url);
    const contentId = url.searchParams.get('content_id');

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

    // Get content record and verify ownership
    const { data: content, error: contentError } = await supabase
      .from('custom_content')
      .select(`
        id,
        title,
        content_type,
        sync_status,
        sync_started_at,
        sync_completed_at,
        sync_error,
        chunk_count,
        page_count,
        file_size_bytes,
        stores!inner(user_id)
      `)
      .eq('id', contentId)
      .single();

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

    // Verify user owns the store
    if (content.stores.user_id !== user.id) {
      return new Response(
        JSON.stringify({ error: 'Access denied' }),
        { status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Calculate progress percentage
    let progressPercent = 0;
    if (content.sync_status === 'completed') {
      progressPercent = 100;
    } else if (content.sync_status === 'processing') {
      progressPercent = 50; // Rough estimate
    } else if (content.sync_status === 'pending') {
      progressPercent = 0;
    }

    // Calculate duration if available
    let durationMs = null;
    if (content.sync_started_at && content.sync_completed_at) {
      const startTime = new Date(content.sync_started_at).getTime();
      const endTime = new Date(content.sync_completed_at).getTime();
      durationMs = endTime - startTime;
    }

    return new Response(
      JSON.stringify({
        success: true,
        contentId: content.id,
        title: content.title,
        contentType: content.content_type,
        status: content.sync_status,
        progress: progressPercent,
        chunkCount: content.chunk_count,
        pageCount: content.page_count,
        fileSize: content.file_size_bytes,
        startedAt: content.sync_started_at,
        completedAt: content.sync_completed_at,
        durationMs: durationMs,
        error: content.sync_error,
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

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