#!/usr/bin/env node

import process from 'node:process'

import { closeDb, query } from '../src/db/client.js'
import { runtimeConfig } from '../src/config/runtime.js'

const RESET_TABLES = [
  'task_runtime_contexts',
  'task_events',
  'claim_tokens',
  'fulfillment_tasks',
  'order_items',
  'orders',
]

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

if (options.help) {
  printHelp()
  process.exit(0)
}

try {
  const counts = await collectCounts()

  printSummary(counts)

  if (!options.apply) {
    console.log('\n当前为预览模式。确认后追加 `--apply` 执行清库。')
    process.exit(0)
  }

  await query(`TRUNCATE TABLE ${RESET_TABLES.join(', ')} RESTART IDENTITY CASCADE`)

  console.log('\n已清空测试业务数据。')
  console.log('保留内容：fulfillment profiles/bindings、admin users、配置文件。')
} catch (error) {
  console.error(
    '\n清理失败：',
    error instanceof Error ? error.message : String(error || '未知错误'),
  )
  process.exitCode = 1
} finally {
  await closeDb()
}

async function collectCounts() {
  const output = []

  for (const tableName of RESET_TABLES) {
    const result = await query(`SELECT COUNT(*)::int AS total FROM ${tableName}`)
    output.push({
      tableName,
      total: Number(result.rows[0]?.total || 0),
    })
  }

  return output
}

function parseArgs(argv) {
  return {
    apply: argv.includes('--apply'),
    help: argv.includes('-h') || argv.includes('--help'),
  }
}

function printHelp() {
  console.log(
    `
用法:
  npm run cleanup:dev-data -- [--apply]

说明:
  基于当前 PostgreSQL fulfillment schema 清空测试业务数据。
  默认只预览各表记录数，追加 --apply 后执行 TRUNCATE。

会清空:
  ${RESET_TABLES.join('\n  ')}

会保留:
  fulfillment_profiles / fulfillment_profile_requirements / sku_fulfillment_bindings
  admin_users / admin_audit_logs
  本地配置文件
  数据库连接: ${String(runtimeConfig.database?.url || '').trim() || '(未配置 DATABASE_URL)'}
`.trim(),
  )
}

function printSummary(counts) {
  const totalRows = counts.reduce((sum, item) => sum + item.total, 0)

  console.log('准备清理当前测试业务数据：')
  for (const item of counts) {
    console.log(`- ${item.tableName}: ${item.total}`)
  }
  console.log(`- total: ${totalRows}`)
}
