/**
 * Custom Content List Edge Function
 *
 * Lists all custom content for a store
 *
 * GET /custom-content-list?store_id={uuid}&content_type={optional}
 */

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 parameters
    const url = new URL(req.url);
    const storeId = url.searchParams.get('store_id');
    const contentType = url.searchParams.get('content_type');

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

    // Verify user owns the store
    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('id')
      .eq('id', storeId)
      .eq('user_id', user.id)
      .single();

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

    // Build query
    let query = supabase
      .from('custom_content')
      .select('*')
      .eq('store_id', storeId)
      .order('created_at', { ascending: false });

    // Filter by content type if specified
    if (contentType) {
      query = query.eq('content_type', contentType);
    }

    const { data: contentList, error: listError } = await query;

    if (listError) {
      throw listError;
    }

    // Format response
    const formattedContent = contentList.map((item) => ({
      id: item.id,
      title: item.title,
      contentType: item.content_type,
      originalFilename: item.original_filename,
      fileSize: item.file_size_bytes,
      pageCount: item.page_count,
      chunkCount: item.chunk_count,
      syncStatus: item.sync_status,
      syncError: item.sync_error,
      syncStartedAt: item.sync_started_at,
      syncCompletedAt: item.sync_completed_at,
      createdAt: item.created_at,
      updatedAt: item.updated_at,
    }));

    return new Response(
      JSON.stringify({
        success: true,
        content: formattedContent,
        total: formattedContent.length,
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

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