import { PrismaClient } from '@prisma/client';
import Decimal from 'decimal.js';

const prisma = new PrismaClient();

async function main() {
  console.log('Seeding mining-wallet-service database...');

  // 1. 初始化核心系统账户（总部、运营、手续费）
  const systemAccounts = [
    { accountType: 'HEADQUARTERS', name: '总部账户', code: 'HQ' },
    { accountType: 'OPERATION', name: '运营账户', code: 'OP' },
    { accountType: 'FEE', name: '手续费账户', code: 'FEE' },
  ];

  for (const account of systemAccounts) {
    const existing = await prisma.systemAccount.findFirst({
      where: { code: account.code },
    });

    if (!existing) {
      const created = await prisma.systemAccount.create({
        data: {
          accountType: account.accountType as any,
          name: account.name,
          code: account.code,
          isActive: true,
        },
      });

      // 发布系统账户创建事件到 Outbox
      await prisma.outboxEvent.create({
        data: {
          aggregateType: 'SystemAccount',
          aggregateId: created.id,
          eventType: 'WalletSystemAccountCreated',
          topic: 'mining-wallet.system-account.created',
          key: created.code,
          payload: {
            id: created.id,
            accountType: created.accountType,
            name: created.name,
            code: created.code,
            provinceId: null,
            cityId: null,
            shareBalance: 0,
            usdtBalance: 0,
            greenPointBalance: 0,
            frozenShare: 0,
            frozenUsdt: 0,
            totalInflow: 0,
            totalOutflow: 0,
            blockchainAddress: null,
            isActive: created.isActive,
          },
        },
      });

      console.log(`Created system account: ${account.code}`);
    } else {
      console.log(`System account already exists: ${account.code}`);
    }
  }

  // 2. 初始化池账户（积分股池A/B、黑洞池、流通池）
  // 积分股池A: 100亿 (10,000,000,000) - 用于销毁
  // 积分股池B: 200万 (2,000,000) - 用于挖矿分配
  // 总计: 100.02亿 (10,002,000,000)
  // upsert: 已存在时只更新元数据（name/description），不覆盖余额等运营数据
  const poolAccounts = [
    {
      poolType: 'SHARE_POOL_A',
      name: '积分股池A',
      balance: new Decimal('0'), // 初始余额为0，通过区块链充值
      description: '销毁池来源（100亿），通过区块链充值',
    },
    {
      poolType: 'SHARE_POOL_B',
      name: '积分股池B',
      balance: new Decimal('0'), // 初始余额为0，通过区块链充值
      description: '挖矿分配池（200万），通过区块链充值',
    },
    {
      poolType: 'BLACK_HOLE_POOL',
      name: '黑洞池',
      balance: new Decimal('0'),
      targetBurn: new Decimal('10000000000'), // 目标销毁100亿
      description: '销毁的积分股，用于减少流通量',
    },
    {
      poolType: 'CIRCULATION_POOL',
      name: '流通池',
      balance: new Decimal('0'),
      description: '市场流通的积分股',
    },
  ];

  for (const pool of poolAccounts) {
    const created = await prisma.poolAccount.upsert({
      where: { poolType: pool.poolType as any },
      update: {
        // 仅更新元数据，绝不覆盖 balance/targetBurn/remainingBurn
        name: pool.name,
        description: pool.description,
        isActive: true,
      },
      create: {
        poolType: pool.poolType as any,
        name: pool.name,
        balance: pool.balance,
        targetBurn: pool.targetBurn,
        remainingBurn: pool.targetBurn,
        description: pool.description,
        isActive: true,
      },
    });

    console.log(`Upserted pool account: ${pool.poolType}`);
  }

  console.log('Seeding completed!');
}

main()
  .catch((e) => {
    console.error('Seeding failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
