/**
 * Custom Content Upload Edge Function
 *
 * Handles PDF file uploads with deduplication:
 * 1. Receive PDF file + metadata
 * 2. Calculate SHA-256 checksum
 * 3. Check for duplicate (same store + checksum)
 * 4. Upload to Supabase Storage (store_id/uuid.pdf)
 * 5. Create database entry with status='pending'
 * 6. Trigger async processing
 *
 * POST /custom-content-upload
 * Content-Type: multipart/form-data
 * Body:
 *   - file: PDF file
 *   - title: Content title
 *   - store_id: Store UUID
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { calculateChecksum } from '../_shared/pdf-processor.ts';

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

interface UploadRequest {
  file: File;
  title: string;
  store_id: string;
}

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 multipart form data
    const formData = await req.formData();
    const file = formData.get('file') as File | null;
    const title = formData.get('title') as string | null;
    const storeId = formData.get('store_id') as string | null;

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

    // Validate file type
    if (file.type !== 'application/pdf') {
      return new Response(
        JSON.stringify({ error: 'Only PDF files are supported' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Validate file size (10MB limit)
    const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    if (file.size > MAX_FILE_SIZE) {
      return new Response(
        JSON.stringify({ error: 'File size exceeds 10MB limit' }),
        { status: 413, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Verify user owns the store
    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('id, store_name, platform_name')
      .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' } }
      );
    }

    // Read file buffer
    const arrayBuffer = await file.arrayBuffer();
    const fileBuffer = new Uint8Array(arrayBuffer);

    // Calculate checksum
    console.log('[Upload] Calculating checksum...');
    const checksum = await calculateChecksum(fileBuffer);
    console.log('[Upload] Checksum:', checksum);

    // Check for duplicate
    const { data: existingContent, error: duplicateError } = await supabase
      .from('custom_content')
      .select('id, title, created_at')
      .eq('store_id', storeId)
      .eq('file_checksum', checksum)
      .single();

    if (duplicateError && duplicateError.code !== 'PGRST116') { // PGRST116 = not found
      throw duplicateError;
    }

    if (existingContent) {
      // File already exists
      const createdDate = new Date(existingContent.created_at).toLocaleDateString();
      return new Response(
        JSON.stringify({
          error: 'This file already exists',
          duplicate: true,
          existingContent: {
            id: existingContent.id,
            title: existingContent.title,
            uploadedAt: createdDate,
          },
        }),
        { status: 409, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Generate UUID for content
    const { data: newContent, error: insertError } = await supabase
      .from('custom_content')
      .insert({
        store_id: storeId,
        user_id: user.id,
        content_type: 'pdf_upload',
        title: title,
        original_filename: file.name,
        file_checksum: checksum,
        file_size_bytes: file.size,
        sync_status: 'pending',
      })
      .select('id')
      .single();

    if (insertError || !newContent) {
      throw insertError || new Error('Failed to create database entry');
    }

    const contentId = newContent.id;

    // Upload file to Supabase Storage
    const storagePath = `${storeId}/${contentId}.pdf`;
    console.log('[Upload] Uploading to storage:', storagePath);

    const { error: uploadError } = await supabase.storage
      .from('custom-content')
      .upload(storagePath, fileBuffer, {
        contentType: 'application/pdf',
        upsert: false,
      });

    if (uploadError) {
      // Rollback database entry
      await supabase
        .from('custom_content')
        .delete()
        .eq('id', contentId);

      throw uploadError;
    }

    // Update database with storage path
    const { error: updateError } = await supabase
      .from('custom_content')
      .update({
        storage_path_pdf: storagePath,
      })
      .eq('id', contentId);

    if (updateError) {
      console.error('[Upload] Failed to update storage path:', updateError);
    }

    // Trigger async processing
    console.log('[Upload] Triggering async processing for content:', contentId);

    // Call custom-content-process function asynchronously
    // Use Promise.resolve to ensure it fires even if we return early
    const processUrl = `${supabaseUrl}/functions/v1/custom-content-process`;
    Promise.resolve().then(async () => {
      try {
        const response = await fetch(processUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${supabaseServiceKey}`,
          },
          body: JSON.stringify({
            content_id: contentId,
            store_id: storeId,
          }),
        });

        if (!response.ok) {
          const errorText = await response.text();
          console.error('[Upload] Processing trigger failed:', response.status, errorText);
        } else {
          console.log('[Upload] Processing triggered successfully');
        }
      } catch (error) {
        console.error('[Upload] Failed to trigger processing:', error);
      }
    });

    return new Response(
      JSON.stringify({
        success: true,
        contentId: contentId,
        title: title,
        fileName: file.name,
        fileSize: file.size,
        checksum: checksum,
        status: 'pending',
        message: 'File uploaded successfully. Processing started.',
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

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