/**
 * Cloudflare Worker Entry Point for Cron + Next.js
 * This file combines the Cron handler with Next.js via Open Next
 */

export default {
  async scheduled(event: ScheduledEvent, env: any, ctx: any) {
    const timestamp = new Date().toISOString();
    console.log(`\n╔════════════════════════════════════════════╗`);
    console.log(`║  🤖 CLOUDFLARE CRON TRIGGERED            ║`);
    console.log(`║  Time: ${timestamp.substring(0, 19)}                    ║`);
    console.log(`╚════════════════════════════════════════════╝\n`);

    // Build the correct URL
    const baseUrl = env.CF_PAGES_URL 
      ? env.CF_PAGES_URL 
      : env.DOMAIN 
      ? `https://${env.DOMAIN}` 
      : "http://localhost:3000";

    const url = `${baseUrl}/api/admin/eta-scraper`;
    const cronSecret = env.CRON_SECRET || process.env.CRON_SECRET || "dev-secret";

    console.log(`📍 URL: ${url}`);
    console.log(`🔐 Auth: Bearer ${cronSecret.substring(0, 10)}...`);
    console.log(`📋 Body: allContainers=true, force=true\n`);

    try {
      console.log("🌐 Sending POST request to ETA scraper endpoint...");
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${cronSecret}`,
          "Content-Type": "application/json",
          "X-Cron-Secret": cronSecret,
        },
        body: JSON.stringify({
          allContainers: true,
          force: true,
          triggered_by: "cloudflare-cron",
          scheduled_at: timestamp,
        }),
      });

      console.log(`📨 Response Status: ${response.status} ${response.statusText}`);

      const result = await response.json();
      
      if (response.ok) {
        console.log("\n✅ SUCCESS!");
        console.log(`   Scraped: ${result.scrapedCount || 0} containers`);
        console.log(`   Success: ${result.successCount || 0}`);
        console.log(`   Failed: ${result.errorCount || 0}`);
        console.log(`   Message: ${result.message || "OK"}\n`);
      } else {
        console.log("\n❌ FAILED!");
        console.log(`   Error: ${result.error || "Unknown error"}`);
        console.log(`   Details: ${result.message || ""}\n`);
      }
    } catch (error) {
      console.error("\n❌ CRITICAL ERROR!");
      console.error(`   ${error instanceof Error ? error.message : String(error)}\n`);
      throw error;
    }
  },
};
