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

const prisma = new PrismaClient();

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

  // 1. 初始化系统账户的交易账户
  // 这些账户序列号对应 mining-wallet-service 中的系统账户
  const systemAccounts = [
    { accountSequence: 'S0000000001', name: '总部社区' },
    { accountSequence: 'S0000000002', name: '成本费账户' },
    { accountSequence: 'S0000000003', name: '运营费账户' },
    { accountSequence: 'S0000000004', name: 'RWAD底池账户' },
  ];

  for (const account of systemAccounts) {
    const existing = await prisma.tradingAccount.findUnique({
      where: { accountSequence: account.accountSequence },
    });

    if (!existing) {
      const created = await prisma.tradingAccount.create({
        data: {
          accountSequence: account.accountSequence,
          shareBalance: new Decimal(0),
          cashBalance: new Decimal(0),
          frozenShares: new Decimal(0),
          frozenCash: new Decimal(0),
          totalBought: new Decimal(0),
          totalSold: new Decimal(0),
        },
      });

      // 发布交易账户创建事件到 Outbox（用于 mining-admin-service 同步）
      await prisma.outboxEvent.create({
        data: {
          aggregateType: 'TradingAccount',
          aggregateId: created.id,
          eventType: 'TradingAccountCreated',
          topic: 'cdc.trading.outbox',
          key: created.accountSequence,
          payload: {
            accountId: created.id,
            accountSequence: created.accountSequence,
            shareBalance: '0',
            cashBalance: '0',
            frozenShares: '0',
            frozenCash: '0',
            totalBought: '0',
            totalSold: '0',
            createdAt: created.createdAt.toISOString(),
          },
        },
      });

      console.log(`Created trading account for system: ${account.name} (${account.accountSequence})`);
    } else {
      console.log(`Trading account already exists: ${account.name} (${account.accountSequence})`);
    }
  }

  // 2. 初始化交易配置
  const existingConfig = await prisma.tradingConfig.findFirst();
  if (!existingConfig) {
    await prisma.tradingConfig.create({
      data: {
        totalShares: new Decimal('10002000000'), // 100.02亿 总积分股
        burnTarget: new Decimal('10000000000'), // 100亿目标销毁量
        burnPeriodMinutes: 2102400, // 4年 = 365*4*1440 分钟
        minuteBurnRate: new Decimal('4756.468797564687'), // 每分钟销毁率
        isActive: false,
      },
    });
    console.log('Created trading config');
  } else {
    console.log('Trading config already exists');
  }

  // 3. 初始化黑洞账户
  const existingBlackHole = await prisma.blackHole.findFirst();
  if (!existingBlackHole) {
    await prisma.blackHole.create({
      data: {
        totalBurned: new Decimal(0),
        targetBurn: new Decimal('10000000000'), // 100亿目标销毁
        remainingBurn: new Decimal('10000000000'),
      },
    });
    console.log('Created black hole account');
  } else {
    console.log('Black hole account already exists');
  }

  // 4. 绿积分（价格分子）现在由做市商的 cashBalance 提供，不再需要独立的 SharePool

  // 5. 初始化流通池
  const existingCirculationPool = await prisma.circulationPool.findFirst();
  if (!existingCirculationPool) {
    await prisma.circulationPool.create({
      data: {
        totalShares: new Decimal(0),
        totalCash: new Decimal(0),
        totalInflow: new Decimal(0),
        totalOutflow: new Decimal(0),
      },
    });
    console.log('Created circulation pool');
  } else {
    console.log('Circulation pool already exists');
  }

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

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