const {
  sendAutomationFailureAlert,
  sendCriticalErrorAlert,
  sendLowBalanceAlert,
  sendSessionExpiredAlert,
} = require("../../notification/services/emailService");
const { checkSmileBalance } = require("../checks/balanceCheck");
const { checkHttpHealth } = require("../checks/httpHealthCheck");
const {
  checkBrowserHeartbeat,
  checkQueueStatus,
  checkSessionStatus,
} = require("../checks/stateFileCheck");
const logger = require("../utils/logger");

async function notify(result, config) {
  if (result.ok) return { sent: false, skipped: true, reason: "ok" };

  if (config.dryRun) {
    logger.warn("Dry-run alert", {
      alertType: result.type,
      code: result.code,
      message: result.message,
      details: result.details,
    });
    return { sent: false, skipped: true, reason: "dry_run" };
  }

  if (result.type === "lowBalance") {
    return sendLowBalanceAlert(result.details.balance, result.details.currency);
  }

  if (result.type === "sessionExpired") {
    return sendSessionExpiredAlert(result.details.account, result.details);
  }

  if (result.type === "automationFailure") {
    return sendAutomationFailureAlert(result.message, result.details);
  }

  return sendCriticalErrorAlert(result.message, {
    component: result.code,
    ...result.details,
  });
}

async function runChecks(config) {
  const checks = [
    checkHttpHealth,
    checkSmileBalance,
    checkQueueStatus,
    checkBrowserHeartbeat,
    checkSessionStatus,
  ];

  const results = [];
  for (const check of checks) {
    const result = await check(config);
    results.push(result);
    logger.info("Live check completed", {
      code: result.code,
      ok: result.ok,
      details: result.details,
    });

    if (!result.ok) {
      await notify(result, config);
    }
  }

  return {
    ok: results.every((result) => result.ok),
    checkedAt: new Date().toISOString(),
    results,
  };
}

module.exports = {
  runChecks,
};
