import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";
import { isAuthBootstrapEnabled } from "@/lib/runtime-env";
import {
  defaultAuthAccounts,
  defaultAuthRoles
} from "@/features/auth/lib/default-accounts";

export async function ensureAuthBootstrap() {
  if (!isAuthBootstrapEnabled()) {
    return;
  }

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

  const roleMap = Object.fromEntries(
    (
      await prisma.role.findMany({
        where: {
          code: {
            in: defaultAuthRoles.map((role) => role.code)
          }
        }
      })
    ).map((role) => [role.code, role])
  );

  for (const user of defaultAuthAccounts) {
    const role = roleMap[user.roleCode];
    if (!role) {
      throw new Error(`Role ${user.roleCode} gagal dibuat`);
    }

    await prisma.user.upsert({
      where: { email: user.email },
      update: {
        roleId: role.id,
        username: user.username,
        name: user.name,
        passwordHash: hashPassword(user.password),
        emailVerifiedAt: new Date(),
        status: "ACTIVE"
      },
      create: {
        roleId: role.id,
        username: user.username,
        email: user.email,
        name: user.name,
        passwordHash: hashPassword(user.password),
        emailVerifiedAt: new Date(),
        status: "ACTIVE"
      }
    });
  }
}
