import {
  getWorkCategoryByKey,
  getWorkerLevelByKey,
  upsertWorkCategory,
  upsertWorkerLevel,
} from '../../repositories/worker-platform/index.js'
import { nowIso } from '../../utils/time.js'
import { DEFAULT_CATEGORY_KEY, DEFAULT_LEVEL_KEY, DEFAULT_LEVEL_NAME } from './mappers.js'

export async function ensureWorkerPlatformDefaults() {
  const now = nowIso()
  const existingLevel = await getWorkerLevelByKey(DEFAULT_LEVEL_KEY)
  const level =
    existingLevel ||
    (await upsertWorkerLevel({
      levelKey: DEFAULT_LEVEL_KEY,
      name: DEFAULT_LEVEL_NAME,
      sortOrder: 10,
      status: 'active',
      permissionJson: JSON.stringify({
        depositFreeAmount: 0,
        maxActiveOrders: 1,
        upgradeThreshold: 0,
      }),
      now,
    }))
  const existingCategory = await getWorkCategoryByKey(DEFAULT_CATEGORY_KEY)
  const category =
    existingCategory ||
    (await upsertWorkCategory({
      categoryKey: DEFAULT_CATEGORY_KEY,
      name: '默认分类',
      sortOrder: 100,
      status: 'active',
      now,
    }))
  return { level, category }
}
