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

const prisma = new PrismaClient();

async function main() {
  const email = process.env.SEED_ADMIN_EMAIL || 'admin@indianbooksworldwide.com';
  const password = process.env.SEED_ADMIN_PASSWORD;

  if (!password) {
    throw new Error('SEED_ADMIN_PASSWORD is required. The seed never installs a shared default password.');
  }

  const passwordHash = await bcrypt.hash(password, 12);
  await prisma.admin.upsert({
    where: { email },
    create: {
      email,
      password: passwordHash,
      name: process.env.SEED_ADMIN_NAME || 'Catalog Administrator',
      role: Role.ADMIN,
      permissions: { catalog: true, imports: true, orders: true },
    },
    update: {
      password: passwordHash,
      name: process.env.SEED_ADMIN_NAME || 'Catalog Administrator',
    },
  });

  console.log(`Admin account is ready: ${email}`);
}

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