import { PrismaClient } from '@prisma/client';
import * as bcrypt from 'bcrypt';

const prisma = new PrismaClient();

// ============================================
// 系统账户定义
// 系统账户使用特殊序列号格式: S + 00000 + 序号 (S0000000001 ~ S0000000004)
// ============================================
// ============================================
// 管理员账户定义
// 默认管理员密码: Admin@123456
// ============================================
const ADMIN_ACCOUNTS = [
  {
    email: 'admin@rwadurian.com',
    password: 'Admin@123456',
    nickname: '超级管理员',
    role: 'super_admin',
  },
];

const SYSTEM_ACCOUNTS = [
  {
    userId: BigInt(1),
    accountSequence: 'S0000000001',  // 总部社区
    nickname: '总部',
    referralCode: 'HQ000001',
    status: 'SYSTEM',
  },
  {
    userId: BigInt(2),
    accountSequence: 'S0000000002',  // 成本费账户
    nickname: '成本费账户',
    referralCode: 'COST0002',
    status: 'SYSTEM',
  },
  {
    userId: BigInt(3),
    accountSequence: 'S0000000003',  // 运营费账户
    nickname: '运营费账户',
    referralCode: 'OPER0003',
    status: 'SYSTEM',
  },
  {
    userId: BigInt(4),
    accountSequence: 'S0000000004',  // RWAD底池账户
    nickname: 'RWAD底池账户',
    referralCode: 'POOL0004',
    status: 'SYSTEM',
  },
  {
    userId: BigInt(5),
    accountSequence: 'D25129999999',  // 种子用户 (特殊序号，区别于真实用户)
    nickname: '种子用户',
    referralCode: 'SEED01',
    status: 'ACTIVE',  // 必须是 ACTIVE 才能作为推荐人
  },
];

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

  // 检查是否已有用户数据，如果有则跳过 seed（防止数据丢失）
  const existingUserCount = await prisma.userAccount.count();
  if (existingUserCount > 5) {
    console.log(`Database already has ${existingUserCount} users, skipping seed to prevent data loss.`);
    console.log('Seed is only intended for initial database setup.');
    return;
  }

  // 确保账户序列号生成器存在（不删除，使用 upsert）
  const today = new Date();
  const year = String(today.getFullYear()).slice(-2);
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  const dateKey = `${year}${month}${day}`;

  // 只有当序列号生成器不存在时才创建
  const existingGenerator = await prisma.accountSequenceGenerator.findFirst();
  if (!existingGenerator) {
    await prisma.accountSequenceGenerator.create({
      data: {
        id: 1,
        dateKey: dateKey,
        currentSequence: 0,
      },
    });
    console.log(`Initialized account sequence generator for date ${dateKey}`);
  } else {
    console.log(`Account sequence generator already exists (dateKey=${existingGenerator.dateKey}, seq=${existingGenerator.currentSequence})`);
  }

  // 创建系统账户（使用 upsert，不会删除现有数据）
  console.log('Ensuring system accounts exist...');
  for (const account of SYSTEM_ACCOUNTS) {
    await prisma.userAccount.upsert({
      where: { userId: account.userId },
      update: {
        nickname: account.nickname,
        referralCode: account.referralCode,
        status: account.status,
      },
      create: account,
    });
    console.log(`  - Ensured system account: ${account.nickname} (accountSequence=${account.accountSequence})`);
  }

  // 创建管理员账户（使用 upsert，不会删除现有数据）
  console.log('Ensuring admin accounts exist...');
  for (const admin of ADMIN_ACCOUNTS) {
    const existing = await prisma.adminAccount.findUnique({
      where: { email: admin.email },
    });

    if (!existing) {
      const passwordHash = await bcrypt.hash(admin.password, 10);
      await prisma.adminAccount.create({
        data: {
          email: admin.email,
          passwordHash,
          nickname: admin.nickname,
          role: admin.role,
          status: 'ACTIVE',
        },
      });
      console.log(`  - Created admin account: ${admin.email} (role=${admin.role})`);
    } else {
      console.log(`  - Admin account already exists: ${admin.email}`);
    }
  }

  console.log('Database seed completed successfully!');
  console.log(`- System accounts ensured (${SYSTEM_ACCOUNTS.length})`);
  console.log(`- Admin accounts ensured (${ADMIN_ACCOUNTS.length})`);
}

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