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

const prisma = new PrismaClient();

/**
 * Mining Service 数据库初始化
 *
 * 需求:
 * - 积分股共 100.02 亿
 * - 200 万原始积分股作为全网贡献值分配
 * - 第一个两年分配 100 万，第二个两年分配 50 万（减半）
 * - 100 亿通过销毁机制进入黑洞（10年完成）
 * - 每秒分配一次，用户实时看到收益
 */
async function main() {
  console.log('🚀 Mining-service seed starting...\n');

  const now = new Date();

  // 常量
  const TOTAL_SHARES = new Decimal('10002000000'); // 100.02亿
  const DISTRIBUTION_POOL = new Decimal('2000000'); // 200万
  const ERA1_DISTRIBUTION = new Decimal('1000000'); // 100万（第一个两年）
  const BURN_TARGET = new Decimal('10000000000'); // 100亿

  // 每秒分配量计算: 100万 / (2年 * 365天 * 24小时 * 60分钟 * 60秒)
  const SECONDS_IN_2_YEARS = 2 * 365 * 24 * 60 * 60; // 63,072,000秒
  const SECOND_DISTRIBUTION = ERA1_DISTRIBUTION.dividedBy(SECONDS_IN_2_YEARS);

  // 1. MiningConfig - 挖矿配置（不激活，等待管理员手动启动）
  await prisma.miningConfig.upsert({
    where: { id: 'default' },
    create: {
      id: 'default',
      totalShares: TOTAL_SHARES,
      distributionPool: DISTRIBUTION_POOL,
      remainingDistribution: ERA1_DISTRIBUTION,
      halvingPeriodYears: 2,
      currentEra: 1,
      eraStartDate: now,
      secondDistribution: SECOND_DISTRIBUTION,
      isActive: false, // 等待管理员在后台启动
      activatedAt: null,
    },
    update: {},
  });
  console.log('✅ MiningConfig initialized (inactive, waiting for admin activation)');

  // 2. BlackHole - 黑洞账户
  await prisma.blackHole.upsert({
    where: { id: 'default' },
    create: {
      id: 'default',
      totalBurned: 0,
      targetBurn: BURN_TARGET,
      remainingBurn: BURN_TARGET,
    },
    update: {},
  });
  console.log('✅ BlackHole initialized');

  // 3. MiningEra - 第一纪元
  await prisma.miningEra.upsert({
    where: { eraNumber: 1 },
    create: {
      eraNumber: 1,
      startDate: now,
      initialDistribution: ERA1_DISTRIBUTION,
      totalDistributed: 0,
      secondDistribution: SECOND_DISTRIBUTION,
      isActive: true,
    },
    update: {},
  });
  console.log('✅ MiningEra 1 initialized');

  // 4. PoolAccounts - 池账户
  const pools = [
    { poolType: 'SHARE_POOL', name: '积分股池', balance: TOTAL_SHARES },
    { poolType: 'BLACK_HOLE_POOL', name: '黑洞池', balance: new Decimal(0) },
    { poolType: 'CIRCULATION_POOL', name: '流通池', balance: new Decimal(0) },
  ];

  for (const pool of pools) {
    await prisma.poolAccount.upsert({
      where: { poolType: pool.poolType as any },
      create: {
        poolType: pool.poolType as any,
        name: pool.name,
        balance: pool.balance,
        totalInflow: pool.balance,
        totalOutflow: 0,
        isActive: true,
      },
      update: {},
    });
  }
  console.log('✅ PoolAccounts initialized');

  // 输出配置
  console.log('\n📊 Configuration:');
  console.log(`   Total Shares: ${TOTAL_SHARES.toFixed(0)} (100.02B)`);
  console.log(`   Distribution Pool: ${DISTRIBUTION_POOL.toFixed(0)} (200万)`);
  console.log(`   Era 1 Distribution: ${ERA1_DISTRIBUTION.toFixed(0)} (100万)`);
  console.log(`   Seconds in 2 Years: ${SECONDS_IN_2_YEARS}`);
  console.log(`   Second Distribution: ${SECOND_DISTRIBUTION.toFixed(12)}`);
  console.log(`   Burn Target: ${BURN_TARGET.toFixed(0)} (100亿, 10年完成)`);
  console.log(`   Mining Active: false (需要在管理后台手动启动)`);

  console.log('\n🎉 Mining-service seed completed!');
}

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