import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { CodereadrApi } from '../../../lib/codereadr-api';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { ticketUuid, eventId, scannedBy } = await request.json();

    if (!ticketUuid || !eventId || !scannedBy) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Missing required parameters' 
      }), { status: 400 });
    }

    // Get CodeREADr configuration for this event
    const { data: config, error: configError } = await supabase
      .from('codereadr_configs')
      .select('*')
      .eq('event_id', eventId)
      .eq('status', 'active')
      .single();

    if (configError || !config) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'CodeREADr not configured for this event' 
      }), { status: 404 });
    }

    // Initialize CodeREADr API
    const codereadrApi = new CodereadrApi();

    // Validate barcode against CodeREADr database
    const validationResult = await codereadrApi.validateBarcode(
      config.database_id,
      ticketUuid
    );

    if (!validationResult || !validationResult.valid) {
      // Log failed scan attempt
      await logScanAttempt(eventId, ticketUuid, scannedBy, 'INVALID_BARCODE', 'Barcode not found in CodeREADr');
      
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Invalid barcode' 
      }), { status: 404 });
    }

    // Parse the response data
    let ticketData;
    try {
      ticketData = JSON.parse(validationResult.response);
    } catch (error) {
      ticketData = { message: validationResult.response };
    }

    // Simulate scan in CodeREADr
    const scanResult = await codereadrApi.simulateScan(
      config.service_id,
      config.user_id,
      ticketUuid
    );

    // Check if ticket exists in our database
    const { data: ticket, error: ticketError } = await supabase
      .from('tickets')
      .select(`
        *,
        events (
          title,
          venue,
          start_time,
          organization_id
        ),
        ticket_types (
          name,
          price
        )
      `)
      .eq('uuid', ticketUuid)
      .single();

    if (ticketError || !ticket) {
      await logScanAttempt(eventId, ticketUuid, scannedBy, 'TICKET_NOT_FOUND', 'Ticket not found in local database');
      
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Ticket not found in local database' 
      }), { status: 404 });
    }

    // Check if ticket is already checked in
    if (ticket.checked_in) {
      await logScanAttempt(eventId, ticketUuid, scannedBy, 'ALREADY_CHECKED_IN', 'Ticket already checked in');
      
      return new Response(JSON.stringify({ 
        success: false, 
        error: `Ticket already checked in at ${new Date(ticket.scanned_at).toLocaleString()}`,
        ticket_data: {
          purchaser_name: ticket.purchaser_name,
          purchaser_email: ticket.purchaser_email,
          event_title: ticket.events?.title,
          checked_in_at: ticket.scanned_at
        }
      }), { status: 400 });
    }

    // Check if ticket belongs to this event
    if (ticket.event_id !== eventId) {
      await logScanAttempt(eventId, ticketUuid, scannedBy, 'WRONG_EVENT', 'Ticket not valid for this event');
      
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Ticket not valid for this event' 
      }), { status: 400 });
    }

    // Update ticket status in our database
    const { error: updateError } = await supabase
      .from('tickets')
      .update({
        checked_in: true,
        scanned_at: new Date().toISOString(),
        scanned_by: scannedBy,
        scan_method: 'codereadr'
      })
      .eq('uuid', ticketUuid);

    if (updateError) {
      await logScanAttempt(eventId, ticketUuid, scannedBy, 'UPDATE_FAILED', 'Failed to update ticket status');
      
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to update ticket status' 
      }), { status: 500 });
    }

    // Log successful scan
    await logScanAttempt(eventId, ticketUuid, scannedBy, 'SUCCESS', 'Ticket successfully checked in via CodeREADr');

    // Return success response
    return new Response(JSON.stringify({
      success: true,
      message: 'Ticket successfully checked in via CodeREADr',
      scan_result: scanResult,
      ticket_data: {
        uuid: ticket.uuid,
        purchaser_name: ticket.purchaser_name,
        purchaser_email: ticket.purchaser_email,
        ticket_type: ticket.ticket_types?.name || 'General',
        price: ticket.ticket_types?.price || 0,
        event_title: ticket.events?.title,
        checked_in_at: new Date().toISOString()
      },
      codereadr_data: ticketData
    }), { status: 200 });

  } catch (error) {

    // Log error
    if (request.body) {
      const body = await request.json();
      await logScanAttempt(
        body.eventId, 
        body.ticketUuid, 
        body.scannedBy, 
        'ERROR', 
        error.message || 'Unknown error'
      );
    }
    
    return new Response(JSON.stringify({ 
      success: false, 
      error: error.message || 'Internal server error' 
    }), { status: 500 });
  }
};

// Helper function to log scan attempts
async function logScanAttempt(
  eventId: string,
  ticketUuid: string,
  scannedBy: string,
  result: string,
  errorMessage?: string
) {
  try {
    await supabase.from('scan_attempts').insert({
      event_id: eventId,
      ticket_uuid: ticketUuid,
      scanned_by: scannedBy,
      result,
      error_message: errorMessage,
      scan_method: 'codereadr',
      timestamp: new Date().toISOString()
    });
  } catch (error) {

  }
}