/**
 * 迁移脚本：将员工月工资复制到合同的 baseSalary
 * 当合同 baseSalary=0 且 performanceSalary=0 时，用员工 monthlySalary 填充 baseSalary
 * 月工资 = baseSalary + performanceSalary
 */
import prisma from '../src/lib/prisma'
import { decrypt } from '../src/lib/crypto'

async function main() {
  const contracts = await prisma.laborContract.findMany({
    where: {
      baseSalary: 0,
      performanceSalary: 0,
    },
    include: {
      employee: {
        select: { monthlySalary: true, baseSalary: true, performanceSalary: true },
      },
    },
  })

  console.log(`找到 ${contracts.length} 个合同 baseSalary=0 且 performanceSalary=0`)

  let updated = 0
  for (const contract of contracts) {
    const emp = contract.employee
    if (!emp?.monthlySalary) continue

    let empBase = 0
    let empPerf = 0
    try {
      empBase = emp.baseSalary ? Number(decrypt(emp.baseSalary)) || 0 : 0
      empPerf = emp.performanceSalary ? Number(decrypt(emp.performanceSalary)) || 0 : 0
    } catch {}

    // 优先用员工的 baseSalary/performanceSalary
    let newBase = empBase
    let newPerf = empPerf

    // 如果员工也没有拆分工资，用 monthlySalary 作为 baseSalary
    if (newBase === 0 && newPerf === 0) {
      let monthly = 0
      try {
        monthly = Number(decrypt(emp.monthlySalary)) || 0
      } catch {}
      if (monthly > 0) {
        newBase = monthly
        newPerf = 0
      }
    }

    if (newBase > 0 || newPerf > 0) {
      await prisma.laborContract.update({
        where: { id: contract.id },
        data: { baseSalary: newBase, performanceSalary: newPerf },
      })
      console.log(`  ✓ 合同 ${contract.id} (员工 ${contract.employeeId}): base=${newBase}, perf=${newPerf}`)
      updated++
    }
  }

  console.log(`\n完成：共更新 ${updated} 个合同`)
}

main()
  .catch(console.error)
  .finally(() => prisma.$disconnect())
