// src/tests/setup/e2e-global-setup.ts
import { execSync } from 'child_process';
import fs from 'node:fs/promises';
import path from 'path';
import os from 'os';
import type { Server } from 'http';
import { logger } from '../../services/logger.server';
import { getPool } from '../../services/db/connection.db';

// --- DEBUG: Log when this file is first loaded/parsed ---
const SETUP_LOAD_TIME = new Date().toISOString();
console.error(`\n[E2E-SETUP-DEBUG] Module loaded at ${SETUP_LOAD_TIME}`);
console.error(`[E2E-SETUP-DEBUG] Current working directory: ${process.cwd()}`);
console.error(`[E2E-SETUP-DEBUG] NODE_ENV: ${process.env.NODE_ENV}`);
console.error(`[E2E-SETUP-DEBUG] __filename: ${import.meta.url}`);

// --- Centralized State for E2E Test Lifecycle ---
let server: Server;
// This will hold the single database pool instance for the entire test run.
let globalPool: ReturnType<typeof getPool> | null = null;
// Temporary directory for test file storage (to avoid modifying committed fixtures)
let tempStorageDir: string | null = null;

/**
 * Cleans all BullMQ queues to ensure no stale jobs from previous test runs.
 * This is critical because old jobs with outdated error messages can pollute test results.
 */
async function cleanAllQueues() {
  console.error(`[PID:${process.pid}] [E2E QUEUE CLEANUP] Starting BullMQ queue cleanup...`);

  try {
    const {
      flyerQueue,
      cleanupQueue,
      emailQueue,
      analyticsQueue,
      weeklyAnalyticsQueue,
      tokenCleanupQueue,
    } = await import('../../services/queues.server');
    console.error(`[E2E QUEUE CLEANUP] Successfully imported queue modules`);

    const queues = [
      flyerQueue,
      cleanupQueue,
      emailQueue,
      analyticsQueue,
      weeklyAnalyticsQueue,
      tokenCleanupQueue,
    ];

    for (const queue of queues) {
      try {
        const jobCounts = await queue.getJobCounts();
        console.error(
          `[E2E QUEUE CLEANUP] Queue "${queue.name}" before cleanup: ${JSON.stringify(jobCounts)}`,
        );

        await queue.obliterate({ force: true });
        console.error(`  [E2E QUEUE CLEANUP] Cleaned queue: ${queue.name}`);
      } catch (error) {
        console.error(
          `  [E2E QUEUE CLEANUP] Could not clean queue ${queue.name}: ${error instanceof Error ? error.message : 'Unknown error'}`,
        );
      }
    }
    console.error(`[PID:${process.pid}] [E2E QUEUE CLEANUP] All queues cleaned successfully.`);
  } catch (error) {
    console.error(
      `[PID:${process.pid}] [E2E QUEUE CLEANUP] CRITICAL ERROR during queue cleanup:`,
      error,
    );
    // Don't throw - we want the tests to continue even if cleanup fails
  }
}

export async function setup() {
  console.error(`\n[E2E-SETUP-DEBUG] ========================================`);
  console.error(`[E2E-SETUP-DEBUG] setup() function STARTED at ${new Date().toISOString()}`);
  console.error(`[E2E-SETUP-DEBUG] ========================================`);

  // Ensure we are in the correct environment for these tests.
  process.env.NODE_ENV = 'test';
  process.env.FRONTEND_URL = 'https://example.com';

  // CRITICAL: Create a temporary directory for test file storage.
  // This prevents tests from modifying or deleting committed fixture files.
  // The temp directory is cleaned up in teardown().
  tempStorageDir = await fs.mkdtemp(path.join(os.tmpdir(), 'flyer-crawler-e2e-'));
  const tempFlyerImagesDir = path.join(tempStorageDir, 'flyer-images');
  await fs.mkdir(path.join(tempFlyerImagesDir, 'icons'), { recursive: true });
  console.error(`[E2E-SETUP] Created temporary storage directory: ${tempFlyerImagesDir}`);

  // CRITICAL: Set STORAGE_PATH before importing the server.
  process.env.STORAGE_PATH = tempFlyerImagesDir;
  console.error(`[E2E-SETUP] Set STORAGE_PATH to temporary directory: ${process.env.STORAGE_PATH}`);

  console.error(`\n--- [PID:${process.pid}] Running E2E Test GLOBAL Setup ---`);
  console.error(`[E2E-SETUP] STORAGE_PATH: ${process.env.STORAGE_PATH}`);
  console.error(`[E2E-SETUP] REDIS_URL: ${process.env.REDIS_URL}`);
  console.error(`[E2E-SETUP] REDIS_PASSWORD is set: ${!!process.env.REDIS_PASSWORD}`);

  // Clean all queues BEFORE running any tests
  console.error(`[E2E-SETUP] About to call cleanAllQueues()...`);
  await cleanAllQueues();
  console.error(`[E2E-SETUP] cleanAllQueues() completed.`);

  // Seed the database for E2E tests
  try {
    console.log(`\n[PID:${process.pid}] Running database seed script for E2E tests...`);
    execSync('npx cross-env NODE_ENV=test npx tsx src/db/seed.ts', { stdio: 'inherit' });
    console.log(`[PID:${process.pid}] Database seed script finished.`);
  } catch (error) {
    console.error('Failed to reset and seed the test database. Aborting E2E tests.', error);
    process.exit(1);
  }

  // Initialize the global pool instance once.
  console.log(`[PID:${process.pid}] Initializing global database pool...`);
  globalPool = getPool();

  // Dynamic import AFTER env vars are set
  console.error(`[E2E-SETUP-DEBUG] About to import server module...`);
  const appModule = await import('../../../server');
  console.error(`[E2E-SETUP-DEBUG] Server module imported successfully`);
  const app = appModule.default;
  console.error(`[E2E-SETUP-DEBUG] App object type: ${typeof app}`);

  // Use a dedicated E2E test port (3098) to avoid conflicts with integration tests (3099)
  // and production servers (3001)
  const port = process.env.TEST_PORT || 3098;
  console.error(`[E2E-SETUP-DEBUG] Attempting to start E2E server on port ${port}...`);

  await new Promise<void>((resolve, reject) => {
    let settled = false;
    try {
      server = app.listen(port, () => {
        if (settled) return;
        settled = true;
        console.log(`In-process E2E test server started on port ${port}`);
        console.error(
          `[E2E-SETUP-DEBUG] Server listen callback invoked at ${new Date().toISOString()}`,
        );
        resolve();
      });

      server.on('error', (err: NodeJS.ErrnoException) => {
        if (settled) return;
        settled = true;
        console.error(`[E2E-SETUP-DEBUG] Server error event:`, err.message);
        if (err.code === 'EADDRINUSE') {
          console.error(
            `[E2E-SETUP-DEBUG] Port ${port} is already in use! ` +
              `Set TEST_PORT env var to use a different port.`,
          );
        }
        reject(err);
      });
    } catch (err) {
      if (settled) return;
      settled = true;
      console.error(`[E2E-SETUP-DEBUG] Error during app.listen:`, err);
      reject(err);
    }
  });

  /**
   * Ping the E2E test server to verify it's ready.
   */
  const pingTestBackend = async (): Promise<boolean> => {
    const pingUrl = `http://localhost:${port}/api/health/ping`;
    console.error(`[E2E-SETUP-DEBUG] Pinging: ${pingUrl}`);
    try {
      const response = await fetch(pingUrl);
      console.error(`[E2E-SETUP-DEBUG] Ping response status: ${response.status}`);
      if (!response.ok) {
        console.error(`[E2E-SETUP-DEBUG] Ping response not OK: ${response.statusText}`);
        return false;
      }
      const json = await response.json();
      console.error(`[E2E-SETUP-DEBUG] Ping response JSON:`, JSON.stringify(json));
      return json?.data?.message === 'pong';
    } catch (e) {
      const errMsg = e instanceof Error ? e.message : String(e);
      console.error(`[E2E-SETUP-DEBUG] Ping exception: ${errMsg}`);
      logger.debug({ error: e }, 'Ping failed while waiting for E2E server, this is expected.');
      return false;
    }
  };

  console.error(
    `[E2E-SETUP-DEBUG] Server started, beginning ping loop at ${new Date().toISOString()}`,
  );
  console.error(`[E2E-SETUP-DEBUG] Server address info:`, server.address());

  const maxRetries = 15;
  const retryDelay = 1000;
  for (let i = 0; i < maxRetries; i++) {
    console.error(`[E2E-SETUP-DEBUG] Ping attempt ${i + 1}/${maxRetries}`);
    if (await pingTestBackend()) {
      console.log('E2E backend server is running and responsive.');
      console.error(
        `[E2E-SETUP-DEBUG] setup() function COMPLETED SUCCESSFULLY at ${new Date().toISOString()}`,
      );
      return;
    }
    console.log(
      `[PID:${process.pid}] Waiting for E2E backend server... (attempt ${i + 1}/${maxRetries})`,
    );
    await new Promise((resolve) => setTimeout(resolve, retryDelay));
  }

  console.error(`[E2E-SETUP-DEBUG] All ${maxRetries} ping attempts failed!`);
  console.error(`[E2E-SETUP-DEBUG] Server listening status: ${server.listening}`);
  console.error(`[E2E-SETUP-DEBUG] Server address: ${JSON.stringify(server.address())}`);

  throw new Error('E2E backend server failed to start.');
}

export async function teardown() {
  console.log(`\n--- [PID:${process.pid}] Running E2E Test GLOBAL Teardown ---`);

  // 1. CRITICAL: Close any workers that might still be running from tests.
  // This ensures all background jobs are stopped before we tear down the server/db.
  // Individual test files should close their own workers, but this is a safety net
  // for cases where tests fail/crash before their afterAll hooks run.
  //
  // NOTE: Importing workers.server.ts creates workers as a side effect.
  // If workers were already imported by a test, this just gets the cached module.
  // If not, we'll create and immediately close them - which is fine.
  try {
    console.log('[E2E-TEARDOWN] Attempting to close any running workers...');
    const { closeWorkers } = await import('../../services/workers.server');
    await closeWorkers();
    // Give workers a moment to fully release their Redis connections
    await new Promise((resolve) => setTimeout(resolve, 100));
    console.log('✅ [E2E-TEARDOWN] Workers closed successfully.');
  } catch (error) {
    // Workers might not have been imported/started, or already closed
    console.log(
      `[E2E-TEARDOWN] Workers cleanup note: ${error instanceof Error ? error.message : 'Not initialized or already closed'}`,
    );
  }

  // 2. Close all queues and the Redis connection to prevent orphaned connections.
  try {
    console.log('[E2E-TEARDOWN] Closing queues and Redis connection...');
    const {
      flyerQueue,
      cleanupQueue,
      emailQueue,
      analyticsQueue,
      weeklyAnalyticsQueue,
      tokenCleanupQueue,
    } = await import('../../services/queues.server');
    const { connection } = await import('../../services/redis.server');

    await Promise.all([
      flyerQueue.close(),
      cleanupQueue.close(),
      emailQueue.close(),
      analyticsQueue.close(),
      weeklyAnalyticsQueue.close(),
      tokenCleanupQueue.close(),
    ]);
    await connection.quit();
    console.log('✅ [E2E-TEARDOWN] Queues and Redis connection closed.');
  } catch (error) {
    console.error(
      `⚠️ [E2E-TEARDOWN] Error closing queues/Redis: ${error instanceof Error ? error.message : String(error)}`,
    );
  }

  // 3. Stop the server to release any resources it's holding.
  if (server) {
    await new Promise<void>((resolve) => server.close(() => resolve()));
    console.log('✅ In-process E2E test server stopped.');
  }

  // 4. Close the single, shared database pool.
  if (globalPool) {
    await globalPool.end();
    console.log('✅ E2E global database pool teardown complete.');
  }

  // 5. Clean up the temporary storage directory.
  if (tempStorageDir) {
    try {
      await fs.rm(tempStorageDir, { recursive: true, force: true });
      console.log(`✅ Cleaned up E2E temporary storage directory: ${tempStorageDir}`);
    } catch (error) {
      console.error(`⚠️ Warning: Could not clean up E2E temp directory ${tempStorageDir}:`, error);
    }
  }

  // 6. Give async operations a moment to fully settle before Vitest exits.
  await new Promise((resolve) => setTimeout(resolve, 100));
  console.log('✅ [E2E-TEARDOWN] E2E test teardown complete.');
}
