import path from 'path';
import { getDirname } from '../../../../utils/dirname-from-import-meta.util';
import { serviceDeactiveAlertDeps } from './setup-config-change-alert.constant';
import { setupAlert } from '../setup-alert/setup-alert.helper';
import { SetupServiceDeactiveAlertArgs } from './setup-service-deactive-alert.type';
import { info } from 'console';

const dirname = getDirname(import.meta);

export const setupServiceDeactiveAlert = async (service: string) => {
  const alertName = `${service}_deactivated`;
  const metricName = `${service}.status_change`;
  const config = await (await import('../../../config/config.helper')).loadConfig();
  const healthdPath = config?.healthdPath;
  const healthScriptsPath = config?.healthScriptsPath;
  if (!healthdPath || !healthScriptsPath) {
    throw new Error(
      'healthdPath and healthScriptsPath must be set in config before calling setupServiceDeactiveAlert.',
    );
  }
  const baseAlertDir = path.join(healthScriptsPath, alertName);
  const scriptPath = `${baseAlertDir}/update-${alertName}-status.sh`;
  const healthAlertPath = path.join(healthdPath, `${alertName}.conf`);
  const scriptDir = path.join(dirname);

  await setupAlert({
    alertName,
    dependencies: serviceDeactiveAlertDeps,
    templates: [
      {
        templatePath: path.join(
          scriptDir,
          'update-service-deactive-status.template.sh',
        ),
        destinationPath: scriptPath,
        replacements: {
          __SERVICE__: service,
          __METRIC_NAME__: metricName,
        },
        mode: 0o755,
      },
      {
        templatePath: path.join(
          scriptDir,
          'service-deactive-alert.template.conf',
        ),
        destinationPath: healthAlertPath,
        replacements: {
          __ALERT_NAME__: alertName,
          __ON__: `statsd_${metricName}_gauge`,
        },
      },
    ],
    cronScriptPath: scriptPath,
    healthdPath,
    healthScriptsPath,
    checkFiles: [healthAlertPath],
  });
};
