/**
 * Scraper Webhook Handler
 *
 * Receives webhook notifications from the scraper service when:
 * - Shop scraping status changes
 * - New content is discovered
 * - Scraping jobs complete or fail
 * - Custom URLs are processed
 *
 * This handler primarily logs events and can trigger UI refresh notifications.
 * All content data is retrieved on-demand from the scraper API.
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.39.3';

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

interface WebhookPayload {
  shop_id: string;
  custom_id?: string;
  event_type: 'job_completed' | 'job_failed' | 'content_updated' | 'custom_url_processed';
  timestamp: string;
  data?: Record<string, any>;
}

Deno.serve(async (req) => {
  // Handle CORS preflight requests
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    // Only accept POST requests
    if (req.method !== 'POST') {
      return new Response(
        JSON.stringify({ error: 'Method not allowed' }),
        {
          status: 405,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        }
      );
    }

    // Parse the webhook payload
    const payload: WebhookPayload = await req.json();

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

    console.log(`Received scraper webhook for shop ${payload.shop_id}: ${payload.event_type}`, payload);

    // Initialize Supabase client
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    // Find the store by the custom_id (which should be the store.id)
    const storeId = payload.custom_id || payload.shop_id;

    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('id, store_name, platform_name, user_id')
      .eq('id', storeId)
      .single();

    if (storeError || !store) {
      console.error('Store not found for scraper webhook:', storeId, storeError);
      return new Response(
        JSON.stringify({ error: 'Store not found' }),
        {
          status: 404,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        }
      );
    }

    // Process different webhook events
    switch (payload.event_type) {
      case 'job_completed':
        console.log(`Scraping job completed for store ${store.store_name} (${store.platform_name})`);
        // Update last scrape timestamp or trigger UI refresh
        // All actual content will be retrieved on-demand from scraper API
        break;

      case 'job_failed':
        console.error(`Scraping job failed for store ${store.store_name}:`, payload.data);
        // Could send notification to store owner about failed scraping
        break;

      case 'content_updated':
        console.log(`New content discovered for store ${store.store_name}:`, payload.data);
        // Could trigger real-time UI updates if needed
        break;

      case 'custom_url_processed':
        console.log(`Custom URL processed for store ${store.store_name}:`, payload.data);
        // Log custom URL processing results
        break;

      default:
        console.warn(`Unknown webhook event type: ${payload.event_type}`);
    }

    // TODO: Could implement real-time notifications here using Supabase realtime
    // For example, insert into a notifications table or publish to a channel

    // Log the webhook event for debugging/monitoring
    const { error: logError } = await supabase
      .from('system_logs')
      .insert({
        log_type: 'scraper_webhook',
        message: `${payload.event_type} for store ${storeId}`,
        details: {
          shop_id: payload.shop_id,
          custom_id: payload.custom_id,
          event_type: payload.event_type,
          timestamp: payload.timestamp,
          data: payload.data,
          store_info: {
            id: store.id,
            name: store.store_name,
            platform: store.platform_name,
          },
        },
        created_at: new Date().toISOString(),
      });

    if (logError) {
      console.error('Failed to log webhook event:', logError);
      // Don't fail the webhook for logging errors
    }

    return new Response(
      JSON.stringify({
        success: true,
        message: 'Webhook processed successfully',
        event_type: payload.event_type,
        shop_id: payload.shop_id,
      }),
      {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      }
    );

  } catch (error) {
    console.error('Error processing scraper webhook:', error);

    return new Response(
      JSON.stringify({
        error: 'Internal server error',
        message: error instanceof Error ? error.message : 'Unknown error',
      }),
      {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      }
    );
  }
});