import { prisma } from "@/lib/prisma";

const FIXED_UNITS = [
  { code: "gr", name: "Gram" },
  { code: "kg", name: "Kilogram" }
] as const;

export async function ensureFixedUnits() {
  return prisma.$transaction(async (tx) => {
    const ensured = [];

    for (const fixedUnit of FIXED_UNITS) {
      const existing =
        (await tx.unit.findFirst({
          where: {
            OR: [
              { code: { equals: fixedUnit.code, mode: "insensitive" } },
              { name: { equals: fixedUnit.name, mode: "insensitive" } }
            ]
          }
        })) ?? null;

      if (existing) {
        ensured.push(
          await tx.unit.update({
            where: { id: existing.id },
            data: {
              code: fixedUnit.code,
              name: fixedUnit.name
            }
          })
        );
        continue;
      }

      ensured.push(
        await tx.unit.create({
          data: fixedUnit
        })
      );
    }

    return ensured.sort((left, right) => {
      const order = ["gr", "kg"];
      return order.indexOf(left.code) - order.indexOf(right.code);
    });
  });
}

export function getFixedUnitLockMessage() {
  return "Master satuan dikunci sistem. Hanya gram dan kilogram yang diperbolehkan.";
}
