import test from 'node:test'
import assert from 'node:assert/strict'

import { normalizeScheduledJobsConfig } from './config-service.js'

test('normalizeScheduledJobsConfig 将旧版 cloudtentacles 阈值迁移为默认账号配置', () => {
  const config = normalizeScheduledJobsConfig({
    enabled: true,
    jobs: [
      {
        id: 'cloudtentacles-health',
        type: 'cloudtentacles_health',
        enabled: true,
        intervalSeconds: 18000,
        cooldownSeconds: 1800,
        config: {
          assetThreshold: 100,
        },
      },
    ],
  })

  assert.deepEqual(config.jobs[0], {
    id: 'cloudtentacles-health',
    type: 'cloudtentacles_health',
    enabled: true,
    intervalSeconds: 18000,
    cooldownSeconds: 1800,
    config: {
      assetThreshold: 100,
      accounts: [
        {
          sourceKey: 'default',
          label: '',
          enabled: true,
          assetThreshold: 100,
        },
      ],
    },
  })
})

test('normalizeScheduledJobsConfig 支持多账号去重并保留 0 阈值', () => {
  const config = normalizeScheduledJobsConfig({
    jobs: [
      {
        id: 'cloudtentacles-health',
        type: 'cloudtentacles_health',
        enabled: true,
        intervalSeconds: 30,
        cooldownSeconds: 10,
        config: {
          assetThreshold: 500,
          accounts: [
            {
              sourceKey: 'default',
              label: '默认账号',
              enabled: true,
              assetThreshold: 0,
            },
            {
              sourceKey: 'default',
              label: '重复账号',
              enabled: false,
              assetThreshold: 999,
            },
            {
              sourceKey: 'account2',
              enabled: false,
              threshold: 200,
            },
          ],
        },
      },
    ],
  })

  assert.deepEqual(config.jobs[0].config.accounts, [
    {
      sourceKey: 'default',
      label: '默认账号',
      enabled: true,
      assetThreshold: 0,
    },
    {
      sourceKey: 'account2',
      label: '',
      enabled: false,
      assetThreshold: 200,
    },
  ])
  assert.equal(config.jobs[0].intervalSeconds, 60)
  assert.equal(config.jobs[0].cooldownSeconds, 60)
})

test('normalizeScheduledJobsConfig 自动补齐数据保留清理任务', () => {
  const config = normalizeScheduledJobsConfig({ enabled: true, jobs: [] })
  const retentionJob = config.jobs.find((job) => job.type === 'data_retention')

  assert.deepEqual(retentionJob, {
    id: 'data-retention',
    type: 'data_retention',
    enabled: true,
    intervalSeconds: 86400,
    config: {},
  })
})
