/**
 * Custom Content View Edge Function
 *
 * Retrieves content for viewing:
 * - For text entries: Returns the content_text directly
 * - For PDFs: Returns both content_text and a signed URL to the PDF
 *
 * GET /custom-content-view?content_id=xxx&store_id=xxx
 */

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 contentId = url.searchParams.get('content_id');
    const storeId = url.searchParams.get('store_id');

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

    // Get content record
    const { data: content, error: contentError } = await supabase
      .from('custom_content')
      .select('*')
      .eq('id', contentId)
      .eq('store_id', storeId)
      .eq('user_id', user.id)
      .single();

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

    // Prepare response based on content type
    const response: any = {
      id: content.id,
      contentType: content.content_type,
      title: content.title,
      contentText: content.content_text,
      originalFilename: content.original_filename,
      pageCount: content.page_count,
      chunkCount: content.chunk_count,
      createdAt: content.created_at,
    };

    // For PDFs, generate signed URL
    if (content.content_type === 'pdf_upload' && content.storage_path_pdf) {
      const { data: signedUrlData, error: signedUrlError } = await supabase.storage
        .from('custom-content')
        .createSignedUrl(content.storage_path_pdf, 3600); // 1 hour expiry

      if (!signedUrlError && signedUrlData) {
        // Replace project subdomain with SUPABASE_URL to hide project ID
        let pdfUrl = signedUrlData.signedUrl;
        const supabaseUrl = Deno.env.get('SUPABASE_URL') || '';

        // Extract the host from SUPABASE_URL (e.g., api.shopcall.ai)
        if (supabaseUrl) {
          try {
            const customHost = new URL(supabaseUrl).host;
            // Replace ztklqodcdjeqpsvhlpud.supabase.co with custom domain
            pdfUrl = pdfUrl.replace(/https:\/\/[^.]+\.supabase\.co/, supabaseUrl);
          } catch (e) {
            console.error('[View] Failed to parse SUPABASE_URL:', e);
          }
        }

        response.pdfUrl = pdfUrl;
      }
    }

    return new Response(
      JSON.stringify(response),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

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