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

export const POST: APIRoute = async ({ request }) => {
  try {
    // This endpoint should be called by a cron job or scheduled task
    // It finds events that are starting soon and sends reminder emails
    
    const now = new Date();
    const oneHourFromNow = new Date(now.getTime() + 60 * 60 * 1000);
    
    // Find events starting within the next hour that have scanner lock enabled
    const { data: events, error } = await supabase
      .from('events')
      .select(`
        id,
        title,
        start_time,
        scanner_lock_enabled,
        scanner_pin_hash,
        scanner_lock_created_by,
        users!scanner_lock_created_by (
          email,
          name
        )
      `)
      .eq('scanner_lock_enabled', true)
      .gte('start_time', now.toISOString())
      .lte('start_time', oneHourFromNow.toISOString());
    
    if (error) {
      console.error('Error fetching events:', error);
      return new Response(JSON.stringify({ error: 'Failed to fetch events' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    if (!events || events.length === 0) {
      return new Response(JSON.stringify({ 
        success: true, 
        message: 'No events found that need reminder emails' 
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const emailPromises = events.map(async (event) => {
      if (!event.users || !event.users.email) {
        console.warn(`No email found for event ${event.id}`);
        return null;
      }
      
      // For security, we can't retrieve the original PIN from the hash
      // So we'll send a reminder without the PIN, asking them to use the original email
      const response = await fetch('/api/send-pin-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          event: {
            id: event.id,
            title: event.title,
            start_time: event.start_time
          },
          pin: '****', // Hide the PIN in reminder
          email: event.users.email,
          type: 'reminder'
        })
      });
      
      const result = await response.json();
      
      if (!response.ok) {
        console.error(`Failed to send reminder email for event ${event.id}:`, result.error);
        return { eventId: event.id, success: false, error: result.error };
      }
      
      return { eventId: event.id, success: true, emailId: result.emailId };
    });
    
    const results = await Promise.allSettled(emailPromises);
    
    const successCount = results.filter(r => r.status === 'fulfilled' && r.value?.success).length;
    const failureCount = results.filter(r => r.status === 'rejected' || (r.status === 'fulfilled' && !r.value?.success)).length;
    
    return new Response(JSON.stringify({
      success: true,
      message: `Processed ${events.length} events`,
      results: {
        total: events.length,
        successful: successCount,
        failed: failureCount
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Send reminder emails error:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};