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

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

    if (!eventId || !organizationId) {
      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('organization_id', organizationId)
      .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();

    // Get all scans from CodeREADr for this service
    const scans = await codereadrApi.getScans(config.service_id);

    let syncedCount = 0;
    let errorCount = 0;
    const errors: string[] = [];

    // Process each scan
    for (const scan of scans) {
      try {
        // 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) {
          continue; // Skip already processed scans
        }

        // Find the corresponding ticket in our database
        const { data: ticket, error: ticketError } = await supabase
          .from('tickets')
          .select('*')
          .eq('uuid', scan.value)
          .eq('event_id', eventId)
          .single();

        if (ticketError || !ticket) {
          errors.push(`Ticket not found for scan ${scan.id}: ${scan.value}`);
          errorCount++;
          continue;
        }

        // Update ticket status if not already checked in
        if (!ticket.checked_in) {
          const { error: updateError } = await supabase
            .from('tickets')
            .update({
              checked_in: true,
              scanned_at: scan.timestamp,
              scan_method: 'codereadr',
              scanned_by: config.user_name
            })
            .eq('uuid', scan.value);

          if (updateError) {
            errors.push(`Failed to update ticket ${scan.value}: ${updateError.message}`);
            errorCount++;
            continue;
          }
        }

        // Record the CodeREADr scan in our database
        await supabase
          .from('codereadr_scans')
          .insert({
            codereadr_scan_id: scan.id,
            event_id: eventId,
            service_id: config.service_id,
            ticket_uuid: scan.value,
            scan_timestamp: scan.timestamp,
            response: scan.response,
            device_id: scan.device_id,
            location: scan.location,
            synced_at: new Date().toISOString()
          });

        syncedCount++;

      } catch (error) {
        errors.push(`Error processing scan ${scan.id}: ${error.message}`);
        errorCount++;
      }
    }

    // Update sync status
    await supabase
      .from('codereadr_configs')
      .update({
        last_sync_at: new Date().toISOString(),
        total_scans: scans.length,
        updated_at: new Date().toISOString()
      })
      .eq('event_id', eventId);

    return new Response(JSON.stringify({
      success: true,
      message: 'Sync completed',
      stats: {
        total_scans: scans.length,
        synced_count: syncedCount,
        error_count: errorCount,
        already_synced: scans.length - syncedCount - errorCount
      },
      errors: errors
    }), { status: 200 });

  } catch (error) {

    return new Response(JSON.stringify({ 
      success: false, 
      error: error.message || 'Failed to sync with CodeREADr' 
    }), { status: 500 });
  }
};

export const GET: APIRoute = async ({ url }) => {
  try {
    const eventId = url.searchParams.get('eventId');
    const organizationId = url.searchParams.get('organizationId');

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

    // Get sync status
    const { data: config, error: configError } = await supabase
      .from('codereadr_configs')
      .select('*')
      .eq('event_id', eventId)
      .eq('organization_id', organizationId)
      .eq('status', 'active')
      .single();

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

    // Get scan statistics
    const { data: scanStats, error: statsError } = await supabase
      .from('codereadr_scans')
      .select('*')
      .eq('event_id', eventId);

    if (statsError) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to fetch scan statistics' 
      }), { status: 500 });
    }

    return new Response(JSON.stringify({
      success: true,
      config: {
        database_id: config.database_id,
        service_id: config.service_id,
        user_id: config.user_id,
        database_name: config.database_name,
        service_name: config.service_name,
        user_name: config.user_name,
        last_sync_at: config.last_sync_at,
        total_scans: config.total_scans,
        status: config.status
      },
      scan_stats: {
        total_synced_scans: scanStats.length,
        recent_scans: scanStats.slice(-10).map(scan => ({
          ticket_uuid: scan.ticket_uuid,
          scan_timestamp: scan.scan_timestamp,
          device_id: scan.device_id,
          synced_at: scan.synced_at
        }))
      }
    }), { status: 200 });

  } catch (error) {

    return new Response(JSON.stringify({ 
      success: false, 
      error: error.message || 'Failed to get CodeREADr status' 
    }), { status: 500 });
  }
};