/**
 * 检查测试账户是否有关联数据（员工/部门），然后删除无关联的测试账户
 */
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

const TEST_IDS = [
  'cmsve0ucj000h5kfta5te1qli', // 几何社保账户
  'cmsve0uea001x5kftbvf9e6zq', // 北公积金账户
  'cmsve0uec001z5kft5sfl4ika', // s公积金账户
  'cmsve0ued00215kft32gmeug5', // sh公积金账户
  'cmsve0uef00235kftz4clk842', // sha公积金账户
  'cmsve0ueg00255kfttwtfeikj', // shan公积金账户
  'cmsve0uei00275kftbwdrkf2n', // shang公积金账户
  'cmsve0uej00295kftc157ts8b', // 上公积金账户
  'cmsve0uek002b5kftnmmsqpfl', // shi公积金账户
  'cmsve0uen002d5kftnzstcqa3', // shi'j公积金账户
  'cmsve0ueo002f5kftxhh9r5lw', // shi'ji公积金账户
  'cmsve0ueq002h5kft2fdu2tlk', // shi'jia公积金账户
  'cmsve0uer002j5kftsi37wcuo', // shi'jia'z公积金账户
  'cmsve0uet002l5kftev27qy7o', // shi'jia'zh公积金账户
  'cmsve0uf5002x5kft16esy662', // 唐山12+6公积金账户
  'cmsve0uf9002z5kft3lx7yl1x', // 几何公积金账户
  'cmsve0ufb00315kftp9mnovag', // 几何5+5公积金账户
]

async function main() {
  console.log('=== 检查关联 ===')
  let canDelete: string[] = []
  let blocked: string[] = []

  for (const id of TEST_IDS) {
    const account = await prisma.socialAccount.findUnique({ where: { id }, select: { name: true, city: true, type: true } })
    if (!account) {
      console.log(`[不存在] ${id}`)
      continue
    }

    const d1 = await prisma.department.count({ where: { socialAccountId: id } })
    const d2 = await prisma.department.count({ where: { housingAccountId: id } })

    if (d1 + d2 > 0) {
      console.log(`[阻止] ${account.type} ${account.name} (${account.city}) — 部门S/H:${d1}/${d2}`)
      blocked.push(id)
    } else {
      console.log(`[可删] ${account.type} ${account.name} (${account.city})`)
      canDelete.push(id)
    }
  }

  console.log(`\n可删除 ${canDelete.length} 个，阻止 ${blocked.length} 个`)

  if (canDelete.length === 0) {
    console.log('无可删除账户')
    return
  }

  // 删除：先删关联的年度标准、社保记录、公积金记录，再删账户
  console.log('\n=== 开始删除 ===')
  for (const id of canDelete) {
    const account = await prisma.socialAccount.findUnique({ where: { id }, select: { name: true } })

    // 删年度标准
    const stdDeleted = await prisma.socialYearStandard.deleteMany({ where: { accountId: id } })
    // 删员工社保记录
    const srDeleted = await prisma.employeeSocialInsRecord.deleteMany({ where: { accountId: id } })
    // 删员工公积金记录
    const hrDeleted = await prisma.employeeHousingFundRecord.deleteMany({ where: { accountId: id } })
    // 删月度处理记录
    const mpDeleted = await prisma.socialMonthlyProcess.deleteMany({ where: { accountId: id } })
    // 删账户
    await prisma.socialAccount.delete({ where: { id } })

    console.log(`[已删] ${account?.name} — 标准:${stdDeleted.count} 社保记录:${srDeleted.count} 公积金记录:${hrDeleted.count} 月度:${mpDeleted.count}`)
  }

  console.log('\n删除完成')
}

main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1) })
