/**
 * CLI 入口：开发环境生成 feifei 领取 mock。
 */
import process from 'node:process'

import { closeDb } from '../src/db/client.js'
import {
  createFeifeiMockClaim,
  isDevMockEnabled,
} from '../src/services/dev-mock/dev-mock-service.js'

type JsonObject = Record<string, unknown>

const args = parseArgs(process.argv.slice(2))

if (args.help) {
  console.log(`
生成 feifei 领取 mock（CLI）。推荐使用后台 /admin/dev-mock。

  npm run mock:feifei -- --step=ready --uid=166909256
`)
  process.exit(0)
}

if (!isDevMockEnabled() && args.force !== true) {
  console.error('当前是生产环境，已拒绝生成 mock 数据。')
  process.exit(1)
}

if (args.force === true) {
  process.env.ENABLE_DEV_MOCK = '1'
}

try {
  const result = await createFeifeiMockClaim({
    step: args.step,
    orderNo: args.orderNo,
    productName: args.productName,
    productCode: args.productCode,
    uid: args.uid,
    h5Url: args.h5Url,
    frontendBaseUrl: args.frontendBaseUrl,
  })

  console.log('已生成 kuaishou-feifei 领取 mock 数据：')
  console.log(`  91订单号：${result.orderNo}`)
  console.log(`  商品：${result.productName}`)
  console.log(`  当前步骤：${result.step}`)
  console.log(`  期望 UID：${result.expectedUid}`)
  console.log(`  领取链接：${result.claimUrl}`)
  for (const tip of result.tips) {
    console.log(`  · ${tip}`)
  }
} catch (error) {
  console.error(error instanceof Error ? error.message : error)
  process.exitCode = 1
} finally {
  await closeDb()
}

function parseArgs(rawArgs: string[]) {
  const parsed: JsonObject = {}
  for (const rawArg of rawArgs) {
    const arg = String(rawArg || '').trim()
    if (!arg) continue
    if (arg === '--help' || arg === '-h') {
      parsed.help = true
      continue
    }
    if (arg === '--force') {
      parsed.force = true
      continue
    }
    const normalized = arg.startsWith('--') ? arg.slice(2) : arg
    const separatorIndex = normalized.indexOf('=')
    if (separatorIndex < 0) {
      parsed[normalized] = true
      continue
    }
    const key = normalized.slice(0, separatorIndex).trim()
    const value = normalized.slice(separatorIndex + 1).trim()
    if (key) parsed[key] = value
  }
  return parsed
}
