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

export const POST: APIRoute = async ({ request }) => {
  try {
    const { barcode_number, event_id, scanned_by } = await request.json();

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

    // Log the scan attempt
    const logScanAttempt = async (result: string, errorMessage?: string) => {
      await supabase.from('scan_attempts').insert({
        barcode_number,
        event_id,
        scanned_by,
        result,
        error_message: errorMessage
      });
    };

    // 1. Lookup ticket by barcode
    const { data: ticket, error: ticketError } = await supabase
      .from('printed_tickets')
      .select(`
        *,
        ticket_types (
          name,
          price
        ),
        events (
          title,
          organization_id
        )
      `)
      .eq('barcode_number', barcode_number)
      .single();

    // 2. Check if barcode exists
    if (ticketError || !ticket) {
      await logScanAttempt('INVALID_BARCODE', 'Barcode not found');
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Invalid barcode' 
      }), { status: 404 });
    }

    // 3. Check if event matches
    if (ticket.event_id !== event_id) {
      await logScanAttempt('WRONG_EVENT', 'Barcode not valid for this event');
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Barcode not valid for this event' 
      }), { status: 400 });
    }

    // 4. Check if already used
    if (ticket.status === 'used') {
      await logScanAttempt('ALREADY_USED', `Ticket already used at ${ticket.checked_in_at}`);
      return new Response(JSON.stringify({ 
        success: false, 
        error: `Ticket already used at ${new Date(ticket.checked_in_at).toLocaleString()}` 
      }), { status: 400 });
    }

    // 5. Check if status is valid
    if (ticket.status !== 'valid') {
      await logScanAttempt('NOT_VALID', 'Ticket is not valid');
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Ticket is not valid' 
      }), { status: 400 });
    }

    // 6. Mark as used
    const { error: updateError } = await supabase
      .from('printed_tickets')
      .update({ 
        status: 'used',
        checked_in_at: new Date().toISOString(),
        scanned_by: scanned_by
      })
      .eq('id', ticket.id);

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

    // 7. Log successful scan
    await logScanAttempt('SUCCESS', 'Check-in successful');

    return new Response(JSON.stringify({ 
      success: true, 
      message: 'Check-in successful',
      ticket: {
        barcode_number: ticket.barcode_number,
        ticket_type: ticket.ticket_types?.name,
        price: ticket.ticket_types?.price,
        event: ticket.events?.title,
        checked_in_at: new Date().toISOString()
      }
    }), { status: 200 });

  } catch (error) {
    console.error('Check-in error:', error);
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};