// Seeds the database with an admin, a demo employee, and the initial
// product categories from the planning doc. Admin can later add more
// categories from /admin/categories without touching this file.

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

const prisma = new PrismaClient();

const SEED_CATEGORIES = [
  'Wheelchair',
  'Power Wheelchair',
  'Daily Living Aids',
  'Lift Chair Recliner',
  'Scooters',
  'Bath and Safety',
  'Hospital Beds',
];

function slugify(input: string): string {
  return input
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-');
}

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

  const adminPassword = await bcrypt.hash('Admin@123', 10);
  const employeePassword = await bcrypt.hash('Employee@123', 10);

  // Upsert ensures re-running the seed does not fail on duplicate emails
  const admin = await prisma.user.upsert({
    where: { email: 'admin@portal.local' },
    update: {},
    create: {
      name: 'Portal Admin',
      email: 'admin@portal.local',
      password: adminPassword,
      role: Role.ADMIN,
    },
  });

  const employee = await prisma.user.upsert({
    where: { email: 'employee@portal.local' },
    update: {},
    create: {
      name: 'Demo Employee',
      email: 'employee@portal.local',
      password: employeePassword,
      role: Role.EMPLOYEE,
    },
  });

  for (let i = 0; i < SEED_CATEGORIES.length; i++) {
    const name = SEED_CATEGORIES[i];
    await prisma.category.upsert({
      where: { slug: slugify(name) },
      update: {},
      create: {
        name,
        slug: slugify(name),
        sortOrder: i,
      },
    });
  }

  console.log('Seed complete.');
  console.log('Admin login:    admin@portal.local / Admin@123');
  console.log('Employee login: employee@portal.local / Employee@123');
}

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