import bcrypt from "bcryptjs";
import { PrismaClient, RoleKey } from "@prisma/client";
import { seedWeeklyKpiBaseline } from "../src/lib/kpis/persistence";
import { ensureExperienceBaseline } from "../src/lib/experienciometro/persistence";
import { ensureHumanCapitalWorkspaceBootstrap } from "../src/lib/human-capital/workspace";

const prisma = new PrismaClient();

async function main() {
  const roles: Array<{ key: RoleKey; name: string }> = [
    { key: "owner", name: "Dueño" },
    { key: "leader", name: "Líder" },
    { key: "employee", name: "Empleado" },
  ];

  for (const role of roles) {
    await prisma.role.upsert({
      where: { key: role.key },
      update: { name: role.name },
      create: role,
    });
  }

  const ownerEmail = (process.env.BOOTSTRAP_OWNER_EMAIL ?? "owner@casabenell.com").toLowerCase().trim();
  const ownerName = process.env.BOOTSTRAP_OWNER_NAME ?? "Owner Casa Benell";
  const ownerPassword = process.env.BOOTSTRAP_OWNER_PASSWORD ?? "ChangeMe123!";
  const ownerPasswordHash = await bcrypt.hash(ownerPassword, 12);

  const owner = await prisma.user.upsert({
    where: { email: ownerEmail },
    update: {
      name: ownerName,
      passwordHash: ownerPasswordHash,
      status: "active",
      emailVerified: new Date(),
    },
    create: {
      email: ownerEmail,
      name: ownerName,
      passwordHash: ownerPasswordHash,
      status: "active",
      emailVerified: new Date(),
    },
  });

  const ownerRole = await prisma.role.findUniqueOrThrow({ where: { key: "owner" } });

  await prisma.userRole.upsert({
    where: {
      userId_roleId: {
        userId: owner.id,
        roleId: ownerRole.id,
      },
    },
    update: {},
    create: {
      userId: owner.id,
      roleId: ownerRole.id,
    },
  });

  await seedWeeklyKpiBaseline(prisma);
  await ensureExperienceBaseline(prisma, owner.id);
  await ensureHumanCapitalWorkspaceBootstrap();

  console.log(`Seed ready. Owner: ${ownerEmail}`);
}

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