import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';

/**
 * CodeREADr Webhook Handler
 * Handles real-time scan notifications from CodeREADr
 */
export const POST: APIRoute = async ({ request }) => {
  try {
    const webhookData = await request.json();
    
    // Validate webhook signature if needed
    // CodeREADr may send a signature header for security
    const signature = request.headers.get('x-codereadr-signature');
    
    // Extract scan data from webhook
    const {
      scan_id,
      service_id,
      user_id,
      value: ticketUuid,
      timestamp,
      response,
      device_id,
      location
    } = webhookData;

    if (!scan_id || !service_id || !ticketUuid) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Invalid webhook data' 
      }), { status: 400 });
    }

    // Find the event based on service_id
    const { data: config, error: configError } = await supabase
      .from('codereadr_configs')
      .select('*')
      .eq('service_id', service_id)
      .eq('status', 'active')
      .single();

    if (configError || !config) {

      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Service configuration not found' 
      }), { status: 404 });
    }

    // Check if we've already processed this scan
    const { data: existingScan } = await supabase
      .from('codereadr_scans')
      .select('id')
      .eq('codereadr_scan_id', scan_id)
      .single();

    if (existingScan) {
      return new Response(JSON.stringify({ 
        success: true, 
        message: 'Scan already processed' 
      }), { status: 200 });
    }

    // Find the corresponding ticket
    const { data: ticket, error: ticketError } = await supabase
      .from('tickets')
      .select(`
        *,
        events (
          title,
          organization_id
        )
      `)
      .eq('uuid', ticketUuid)
      .eq('event_id', config.event_id)
      .single();

    if (ticketError || !ticket) {

      // Record the scan attempt anyway
      await supabase
        .from('codereadr_scans')
        .insert({
          codereadr_scan_id: scan_id,
          event_id: config.event_id,
          service_id: service_id,
          ticket_uuid: ticketUuid,
          scan_timestamp: timestamp,
          response: response,
          device_id: device_id,
          location: location,
          synced_at: new Date().toISOString(),
          webhook_processed: true,
          error_message: 'Ticket not found'
        });

      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Ticket not found' 
      }), { status: 404 });
    }

    // Update ticket status if not already checked in
    let ticketUpdated = false;
    if (!ticket.checked_in) {
      const { error: updateError } = await supabase
        .from('tickets')
        .update({
          checked_in: true,
          scanned_at: timestamp,
          scan_method: 'codereadr',
          scanned_by: user_id || 'codereadr-webhook'
        })
        .eq('uuid', ticketUuid);

      if (updateError) {

      } else {
        ticketUpdated = true;
      }
    }

    // Record the scan in our database
    await supabase
      .from('codereadr_scans')
      .insert({
        codereadr_scan_id: scan_id,
        event_id: config.event_id,
        service_id: service_id,
        ticket_uuid: ticketUuid,
        scan_timestamp: timestamp,
        response: response,
        device_id: device_id,
        location: location,
        synced_at: new Date().toISOString(),
        webhook_processed: true,
        ticket_updated: ticketUpdated
      });

    // Log the scan attempt
    await supabase
      .from('scan_attempts')
      .insert({
        event_id: config.event_id,
        ticket_uuid: ticketUuid,
        scanned_by: user_id || 'codereadr-webhook',
        result: ticketUpdated ? 'SUCCESS' : 'ALREADY_CHECKED_IN',
        error_message: ticketUpdated ? null : 'Ticket already checked in',
        scan_method: 'codereadr',
        timestamp: timestamp
      });

    // Send real-time notification to connected clients
    try {
      await supabase.channel('scan-updates')
        .send({
          type: 'broadcast',
          event: 'ticket-scanned',
          payload: {
            event_id: config.event_id,
            ticket_uuid: ticketUuid,
            scan_timestamp: timestamp,
            purchaser_name: ticket.purchaser_name,
            scan_method: 'codereadr',
            success: ticketUpdated
          }
        });
    } catch (error) {

    }

    return new Response(JSON.stringify({
      success: true,
      message: 'Webhook processed successfully',
      scan_processed: {
        scan_id: scan_id,
        ticket_uuid: ticketUuid,
        event_id: config.event_id,
        ticket_updated: ticketUpdated,
        timestamp: timestamp
      }
    }), { status: 200 });

  } catch (error) {

    return new Response(JSON.stringify({ 
      success: false, 
      error: error.message || 'Webhook processing failed' 
    }), { status: 500 });
  }
};