/**
 * Custom Content Delete Edge Function
 *
 * Deletes custom content (hard delete):
 * 1. Verify ownership
 * 2. Delete from Qdrant
 * 3. Delete files from Storage
 * 4. Delete database record
 *
 * DELETE /custom-content-delete
 * Body: { content_id, store_id }
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { deleteCustomContent } from '../_shared/qdrant-client.ts';

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

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' } }
      );
    }

    console.log(`[Delete] Deleting content ${content_id} from store ${store_id}`);

    // Get content record and verify ownership
    const { data: content, error: contentError } = await supabase
      .from('custom_content')
      .select('*, stores!inner(store_name, user_id, qdrant_url, qdrant_api_key)')
      .eq('id', content_id)
      .eq('store_id', store_id)
      .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' } }
      );
    }

    // Delete from Qdrant
    if (content.qdrant_point_ids && content.qdrant_point_ids.length > 0) {
      console.log(`[Delete] Deleting ${content.qdrant_point_ids.length} points from Qdrant`);

      try {
        const qdrantConfig = content.stores.qdrant_url && content.stores.qdrant_api_key
          ? { url: content.stores.qdrant_url, apiKey: content.stores.qdrant_api_key }
          : undefined;

        await deleteCustomContent(
          content.stores.store_name,
          content.qdrant_point_ids,
          qdrantConfig
        );

        console.log(`[Delete] Successfully deleted from Qdrant`);
      } catch (qdrantError: any) {
        console.error('[Delete] Qdrant deletion error:', qdrantError);
        // Continue with deletion even if Qdrant fails
      }
    }

    // Delete files from Storage
    const filesToDelete: string[] = [];
    if (content.storage_path_pdf) {
      filesToDelete.push(content.storage_path_pdf);
    }
    if (content.storage_path_txt) {
      filesToDelete.push(content.storage_path_txt);
    }

    if (filesToDelete.length > 0) {
      console.log(`[Delete] Deleting ${filesToDelete.length} files from storage`);

      try {
        const { error: storageError } = await supabase.storage
          .from('custom-content')
          .remove(filesToDelete);

        if (storageError) {
          console.error('[Delete] Storage deletion error:', storageError);
          // Continue with deletion even if storage fails
        } else {
          console.log(`[Delete] Successfully deleted files from storage`);
        }
      } catch (storageError: any) {
        console.error('[Delete] Storage deletion error:', storageError);
      }
    }

    // Delete database record
    console.log(`[Delete] Deleting database record`);
    const { error: deleteError } = await supabase
      .from('custom_content')
      .delete()
      .eq('id', content_id);

    if (deleteError) {
      throw deleteError;
    }

    console.log(`[Delete] Successfully deleted content ${content_id}`);

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

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