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

const prisma = new PrismaClient();

const ITEMS = [
  { name: 'Dust Fragment', rarity: 'Consumer', category: 'Misc', marketValue: 5, imageUrl: '' },
  { name: 'Scrap Token', rarity: 'Consumer', category: 'Misc', marketValue: 8, imageUrl: '' },
  { name: 'Plain Cap', rarity: 'Consumer', category: 'Agent', marketValue: 12, imageUrl: '' },
  { name: 'Blue Softpack', rarity: 'Industrial', category: 'Misc', marketValue: 25, imageUrl: '' },
  { name: 'Steel Badge', rarity: 'Industrial', category: 'Sticker', marketValue: 35, imageUrl: '' },
  { name: 'Signal Chip', rarity: 'Industrial', category: 'Misc', marketValue: 40, imageUrl: '' },
  { name: 'Azure Coil', rarity: 'MilSpec', category: 'SMG', marketValue: 80, imageUrl: '' },
  { name: 'Navy Grip', rarity: 'MilSpec', category: 'Pistol', marketValue: 95, imageUrl: '' },
  { name: 'Pulse Meter', rarity: 'MilSpec', category: 'Rifle', marketValue: 110, imageUrl: '' },
  { name: 'Violet Core', rarity: 'Restricted', category: 'Rifle', marketValue: 220, imageUrl: '' },
  { name: 'Phantom Lens', rarity: 'Restricted', category: 'Sniper', marketValue: 280, imageUrl: '' },
  { name: 'Neon Circuit', rarity: 'Restricted', category: 'SMG', marketValue: 320, imageUrl: '' },
  { name: 'Pink Dynamo', rarity: 'Classified', category: 'Rifle', marketValue: 650, imageUrl: '' },
  { name: 'Ruby Flux', rarity: 'Classified', category: 'Heavy', marketValue: 800, imageUrl: '' },
  { name: 'Crimson Edge', rarity: 'Covert', category: 'Knife', marketValue: 1800, imageUrl: '' },
  { name: 'Blood Ember', rarity: 'Covert', category: 'Knife', marketValue: 2400, imageUrl: '' },
  { name: 'Golden Relic', rarity: 'Extraordinary', category: 'Gloves', marketValue: 12000, imageUrl: '' },
  { name: 'Mythic Blade', rarity: 'Extraordinary', category: 'Knife', marketValue: 25000, imageUrl: '' },
];

async function main() {
  await prisma.userAchievement.deleteMany();
  await prisma.achievement.deleteMany();
  await prisma.transaction.deleteMany();
  await prisma.inventoryItem.deleteMany();
  await prisma.caseItem.deleteMany();
  await prisma.case.deleteMany();
  await prisma.item.deleteMany();
  await prisma.user.deleteMany();

  const { ACHIEVEMENT_DEFS } = await import('../src/achievements.js');
  for (const def of ACHIEVEMENT_DEFS) {
    await prisma.achievement.create({ data: def });
  }

  const adminUsername = String(process.env.ADMIN_USERNAME || 'admin').trim() || 'admin';
  const adminPassword = String(process.env.ADMIN_PASSWORD || 'admin123');
  const adminHash = await bcrypt.hash(adminPassword, 10);
  const userHash = await bcrypt.hash('player123', 10);

  await prisma.user.create({
    data: {
      username: adminUsername,
      passwordHash: adminHash,
      balance: 0,
      role: 'admin',
    },
  });

  const demo = await prisma.user.create({
    data: {
      username: 'player',
      passwordHash: userHash,
      balance: 10000,
      osuBalance: 100,
      role: 'user',
    },
  });

  await prisma.transaction.create({
    data: {
      userId: demo.id,
      type: 'seed_credit',
      amount: 10000,
      meta: JSON.stringify({ reason: 'demo_seed' }),
    },
  });

  await prisma.transaction.create({
    data: {
      userId: demo.id,
      type: 'seed_osu',
      amount: 100,
      meta: JSON.stringify({ reason: 'demo_osu' }),
    },
  });

  const items = [];
  for (const data of ITEMS) {
    items.push(await prisma.item.create({ data }));
  }

  const byName = Object.fromEntries(items.map((i) => [i.name, i]));

  const starter = await prisma.case.create({
    data: {
      name: 'Starter Crate',
      imageUrl: '',
      price: 100,
      active: true,
    },
  });

  const arsenal = await prisma.case.create({
    data: {
      name: 'Arsenal Case',
      imageUrl: '',
      price: 250,
      active: true,
    },
  });

  const vault = await prisma.case.create({
    data: {
      name: 'Gold Vault',
      imageUrl: '',
      price: 500,
      active: true,
    },
  });

  const drops = [
    [starter, 'Dust Fragment', 40],
    [starter, 'Scrap Token', 30],
    [starter, 'Plain Cap', 15],
    [starter, 'Blue Softpack', 8],
    [starter, 'Azure Coil', 5],
    [starter, 'Violet Core', 1.5],
    [starter, 'Crimson Edge', 0.4],
    [starter, 'Golden Relic', 0.1],

    [arsenal, 'Steel Badge', 35],
    [arsenal, 'Signal Chip', 25],
    [arsenal, 'Navy Grip', 18],
    [arsenal, 'Pulse Meter', 12],
    [arsenal, 'Phantom Lens', 6],
    [arsenal, 'Pink Dynamo', 2.5],
    [arsenal, 'Blood Ember', 1.2],
    [arsenal, 'Mythic Blade', 0.3],

    [vault, 'Neon Circuit', 40],
    [vault, 'Ruby Flux', 30],
    [vault, 'Crimson Edge', 18],
    [vault, 'Blood Ember', 8],
    [vault, 'Golden Relic', 3],
    [vault, 'Mythic Blade', 1],
  ];

  for (const [c, name, dropRate] of drops) {
    await prisma.caseItem.create({
      data: {
        caseId: c.id,
        itemId: byName[name].id,
        dropRate,
      },
    });
  }

  console.log('Seed complete.');
  console.log(`  admin: ${adminUsername} / ${adminPassword}`);
  console.log('  player / player123 (balance: 100.00, osu: 100)');
  console.log(`  achievements: ${ACHIEVEMENT_DEFS.length} definitions`);
}

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