import { getInterests } from '~/server/utils/nocodb';
import { checkDocumentSignatureStatus } from '~/server/utils/documeso';

// Track if tasks are already scheduled
let tasksScheduled = false;

export async function scheduleEOIReminders() {
  if (tasksScheduled) {
    console.log('[EOI Reminders] Tasks already scheduled');
    return;
  }

  console.log('[EOI Reminders] Scheduling reminder tasks...');

  // Check every hour if it's time to send reminders
  setInterval(async () => {
    const now = new Date();
    const parisTime = new Date(now.toLocaleString('en-US', { timeZone: 'Europe/Paris' }));
    const hour = parisTime.getHours();
    const minute = parisTime.getMinutes();

    // Check if it's 9am or 4pm (16:00)
    if ((hour === 9 || hour === 16) && minute === 0) {
      console.log(`[EOI Reminders] Running ${hour === 9 ? '9am' : '4pm'} reminder check...`);
      await processReminders();
    }
  }, 60000); // Check every minute

  tasksScheduled = true;
  console.log('[EOI Reminders] Tasks scheduled successfully');
}

async function processReminders() {
  try {
    // Get all interests
    const response = await getInterests();
    const interests = response.list || [];

    console.log(`[EOI Reminders] Processing ${interests.length} interests...`);

    for (const interest of interests) {
      try {
        // Skip if no document ID or reminders disabled
        const documentId = (interest as any)['documeso_document_id'];
        const remindersEnabled = (interest as any)['reminder_enabled'] !== false;
        
        if (!documentId || !remindersEnabled) {
          continue;
        }

        // Check if we should send reminder (not sent in last 12 hours)
        const lastReminderSent = (interest as any)['last_reminder_sent'];
        if (lastReminderSent) {
          const lastSentTime = new Date(lastReminderSent).getTime();
          const twelveHoursAgo = Date.now() - (12 * 60 * 60 * 1000);
          if (lastSentTime > twelveHoursAgo) {
            continue; // Skip if reminder sent within last 12 hours
          }
        }

        // Send reminder
        await sendReminder(interest);
      } catch (error) {
        console.error(`[EOI Reminders] Error processing interest ${interest.Id}:`, error);
      }
    }

    console.log('[EOI Reminders] Reminder processing completed');
  } catch (error) {
    console.error('[EOI Reminders] Error in processReminders:', error);
  }
}

async function sendReminder(interest: any) {
  try {
    // Use a full URL for the fetch since we're in a background task
    const baseUrl = process.env.NUXT_PUBLIC_SITE_URL || 'http://localhost:3000';
    const response = await $fetch<{
      success: boolean;
      remindersSent: number;
      results: any[];
      message?: string;
    }>(`${baseUrl}/api/eoi/send-reminders`, {
      method: 'POST',
      headers: {
        'x-tag': '094ut234' // System tag for automated processes
      },
      body: {
        interestId: interest.Id.toString(),
        documentId: (interest as any)['documeso_document_id']
      }
    });

    if (response.success) {
      console.log(`[EOI Reminders] Sent ${response.remindersSent} reminders for interest ${interest.Id}`);
    }
  } catch (error) {
    console.error(`[EOI Reminders] Failed to send reminder for interest ${interest.Id}:`, error);
  }
}

// Export function to manually trigger reminders (for testing)
export async function triggerReminders() {
  console.log('[EOI Reminders] Manually triggering reminder check...');
  await processReminders();
}
