import { PrismaClient } from "@prisma/client"
import bcrypt from "bcryptjs"

const db = new PrismaClient()

async function main() {
  // Seed Kuwait country
  await db.country.upsert({
    where: { countryCode: "KW" },
    update: {},
    create: {
      countryCode: "KW",
      countryName: "Kuwait",
      currencyCode: "KWD",
      currencySymbol: "د.ك",
      decimalPlaces: 3,
      taxLabel: "VAT",
      taxPercent: 0,
      hasTax: false,
      status: true,
    },
  })
  console.log("Country seeded: Kuwait")

  const superAdminRole = await db.role.upsert({
    where: { name: "SUPER_ADMIN" },
    update: {},
    create: { name: "SUPER_ADMIN" },
  })

  await db.role.upsert({
    where: { name: "HR_MANAGER" },
    update: {},
    create: { name: "HR_MANAGER" },
  })

  await db.role.upsert({
    where: { name: "EMPLOYEE" },
    update: {},
    create: { name: "EMPLOYEE" },
  })

  const existingWildcardPerm = await db.permission.findFirst({
    where: {
      roleId: superAdminRole.id,
      module: "*",
    },
  })

  if (!existingWildcardPerm) {
    await db.permission.create({
      data: {
        roleId: superAdminRole.id,
        module: "*",
        actions: ["view", "create", "edit", "delete"],
      },
    })
  }

  const existing = await db.user.findUnique({
    where: { email: "admin@gmail.com" },
  })

  if (existing) {
    const hasRole = await db.userRole.findFirst({
      where: {
        userId: existing.id,
        roleId: superAdminRole.id,
      },
    })

    if (!hasRole) {
      await db.userRole.create({
        data: {
          userId: existing.id,
          roleId: superAdminRole.id,
        },
      })
      console.log("Assigned SUPER_ADMIN role to existing admin")
    } else {
      console.log("Admin already exists")
    }

    return
  }

  const hashedPassword = await bcrypt.hash("admin123", 12)

  const admin = await db.user.create({
    data: {
      name: "Super Admin",
      email: "admin@gmail.com",
      password: hashedPassword,
      isActive: true,
      roles: {
        create: {
          roleId: superAdminRole.id,
        },
      },
    },
  })

  console.log("Admin created:", admin.email)
}

main()
  .catch(console.error)
  .finally(() => db.$disconnect())