import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { schedulerDisabled } from '../src/queues/scheduler-switch';

/**
 * 定时任务写侧总闸(PAC_SCHEDULER_DISABLED)。
 *
 * 【为什么必须是代码开关】迁移窗口里新旧实例并存,新实例绝不能同时跑增量摄入 + 重算。
 * 但 jvs-dw 的 manifest 写死 `auto_sync: true`、cron 也写在 manifest(优先级高于全局 env),
 * `PAC_INCREMENTAL_HOSTS=` 留空只 fallback 到自动发现 —— **靠 env 关不掉**;
 * 改 manifest 又会被 deploy 的 `git pull` 覆盖。
 *
 * 【边界】只关"写",不关"读":dw-lag-monitor / daily-health-report 只发告警和报表,
 * 备用实例照常跑反而多一双眼睛。这条边界如果被后来人"顺手统一"掉,迁移期就会静默失去监控 ——
 * 故用测试钉住。
 */
const read = (f: string) => readFileSync(join(__dirname, '../src/queues', f), 'utf-8');

describe('PAC_SCHEDULER_DISABLED', () => {
  const ORIG = process.env.PAC_SCHEDULER_DISABLED;
  afterEach(() => {
    if (ORIG === undefined) delete process.env.PAC_SCHEDULER_DISABLED;
    else process.env.PAC_SCHEDULER_DISABLED = ORIG;
  });

  test('未设置 → false(默认跑,既有部署行为不变)', () => {
    delete process.env.PAC_SCHEDULER_DISABLED;
    expect(schedulerDisabled()).toBe(false);
  });

  test('=1 → true', () => {
    process.env.PAC_SCHEDULER_DISABLED = '1';
    expect(schedulerDisabled()).toBe(true);
  });

  test('⭐ 只认严格的 "1" —— "true"/"yes"/"0" 都不算,避免似是而非地半开', () => {
    for (const v of ['true', 'yes', 'on', '0', '', ' 1 ']) {
      process.env.PAC_SCHEDULER_DISABLED = v;
      expect(schedulerDisabled()).toBe(false);
    }
  });
});

describe('闸门覆盖范围 — 只关写侧', () => {
  test('⭐ 增量摄入(会改数据)受闸控,且连僵尸锁回收一并跳过', () => {
    const s = read('sync-incremental.scheduler.ts');
    expect(s).toContain('schedulerDisabled()');
    // 闸判定必须在 reapStaleRunningLocks 之前 —— 共库场景下回收会误清老实例正在跑的锁
    expect(s.indexOf('schedulerDisabled()')).toBeLessThan(s.indexOf('await this.reapStaleRunningLocks()'));
  });

  test('⭐ persona stale-scan(会 enqueue 重算)受闸控', () => {
    expect(read('stale-scan.service.ts')).toContain('schedulerDisabled()');
  });

  test('⭐ 只读任务不受闸控 —— 迁移期仍要有监控和日报', () => {
    expect(read('dw-lag-monitor.service.ts')).not.toContain('schedulerDisabled');
    expect(read('daily-health-report.service.ts')).not.toContain('schedulerDisabled');
  });
});
