// Task to process sales emails for EOI documents
import { $fetch } from 'ofetch';

let taskScheduled = false;

export function scheduleEmailProcessing() {
  if (taskScheduled) {
    console.log('[Process Sales Emails] Task already scheduled');
    return;
  }

  console.log('[Process Sales Emails] Scheduling email processing task...');

  // Process emails every 30 minutes
  setInterval(async () => {
    console.log('[Process Sales Emails] Running email check...');
    await processEmails();
  }, 30 * 60 * 1000); // 30 minutes

  // Also run immediately on startup
  setTimeout(() => {
    processEmails();
  }, 10000); // 10 seconds after startup

  taskScheduled = true;
  console.log('[Process Sales Emails] Task scheduled successfully');
}

async function processEmails() {
  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(`${baseUrl}/api/email/process-sales-eois`, {
      method: 'POST',
      headers: {
        'x-tag': '094ut234' // System tag for automated processes
      }
    });

    if (response.success) {
      console.log(`[Process Sales Emails] Processed ${response.processed} emails`);
      if (response.results && response.results.length > 0) {
        response.results.forEach((result: any) => {
          if (result.processed) {
            console.log(`[Process Sales Emails] Successfully processed EOI for ${result.clientName}`);
          } else {
            console.log(`[Process Sales Emails] Failed to process EOI: ${result.error}`);
          }
        });
      }
    }
  } catch (error) {
    console.error('[Process Sales Emails] Error processing emails:', error);
  }
}

// Export function to manually trigger processing (for testing)
export async function triggerEmailProcessing() {
  console.log('[Process Sales Emails] Manually triggering email processing...');
  await processEmails();
}
