/**
 * Custom Content Create Edge Function
 *
 * Creates text-based custom content entries:
 * 1. Validate input
 * 2. Create database entry
 * 3. Chunk text if needed
 * 4. Generate embeddings
 * 5. Store in Qdrant
 * 6. Update database with results
 *
 * POST /custom-content-create
 * Body: { title, content_text, store_id }
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { chunkText } from '../_shared/text-chunker.ts';
import { syncCustomContent } from '../_shared/qdrant-client.ts';
import { validateContent } from '../_shared/content-validator.ts';

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 { title, content_text, store_id } = await req.json();

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

    // Validate content length
    if (content_text.trim().length === 0) {
      return new Response(
        JSON.stringify({ error: 'Content text cannot be empty' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    if (content_text.length > 50000) {
      return new Response(
        JSON.stringify({ error: 'Content text exceeds maximum length of 50,000 characters' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Validate content format (reject code/structured data)
    const validationResult = validateContent(content_text);
    if (!validationResult.isValid) {
      return new Response(
        JSON.stringify({
          error: validationResult.reason || 'Invalid content format',
          detectedFormat: validationResult.detectedFormat,
        }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

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

    console.log(`[Create] Creating text entry for store ${store_id}`);

    // Create database entry
    const { data: newContent, error: insertError } = await supabase
      .from('custom_content')
      .insert({
        store_id: store_id,
        user_id: user.id,
        content_type: 'text_entry',
        title: title,
        content_text: content_text,
        sync_status: 'processing',
        sync_started_at: new Date().toISOString(),
      })
      .select('id, created_at')
      .single();

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

    const contentId = newContent.id;

    try {
      // Combine title and content for chunking
      // Title is prepended to content so it's searchable in the knowledge base
      const fullText = `${title}\n${content_text}`;

      // Chunk text using hybrid strategy
      console.log(`[Create] Chunking text...`);
      const chunkResult = chunkText(fullText);
      console.log(`[Create] Created ${chunkResult.chunks.length} chunks using ${chunkResult.strategy} strategy`);

      // Get Qdrant config from store
      const qdrantConfig = store.qdrant_url && store.qdrant_api_key
        ? { url: store.qdrant_url, apiKey: store.qdrant_api_key }
        : undefined;

      // Sync to Qdrant
      console.log(`[Create] Syncing to Qdrant...`);
      const pointIds = await syncCustomContent(
        store_id,
        contentId,
        store.store_name,
        chunkResult.chunks,
        {
          title: title,
          contentType: 'text_entry',
          createdAt: newContent.created_at,
        },
        qdrantConfig
      );

      console.log(`[Create] Synced ${pointIds.length} points to Qdrant`);

      // Update database with success
      await supabase
        .from('custom_content')
        .update({
          chunk_count: chunkResult.chunks.length,
          qdrant_point_ids: pointIds,
          sync_status: 'completed',
          sync_completed_at: new Date().toISOString(),
          sync_error: null,
        })
        .eq('id', contentId);

      console.log(`[Create] Successfully created content ${contentId}`);

      return new Response(
        JSON.stringify({
          success: true,
          contentId: contentId,
          title: title,
          chunkCount: chunkResult.chunks.length,
          strategy: chunkResult.strategy,
          qdrantPoints: pointIds.length,
          status: 'completed',
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );

    } catch (processingError: any) {
      console.error('[Create] Processing error:', processingError);

      // Update database with error
      await supabase
        .from('custom_content')
        .update({
          sync_status: 'failed',
          sync_completed_at: new Date().toISOString(),
          sync_error: processingError.message || processingError.toString(),
        })
        .eq('id', contentId);

      throw processingError;
    }

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