import { prisma } from "@pmap/database";

const referenceSettingKey = "participant_reference";
const defaultReferencePrefix = "Ref-AC2026";

type ReferenceSettingValue = {
  prefix?: string;
};

function readPrefix(value: unknown) {
  if (value && typeof value === "object" && "prefix" in value) {
    const prefix = (value as ReferenceSettingValue).prefix;
    if (typeof prefix === "string" && prefix.trim()) return prefix.trim();
  }
  return defaultReferencePrefix;
}

export async function getParticipantReferencePrefix() {
  const setting = await prisma.systemSetting.findFirst({
    where: { conferenceId: null, key: referenceSettingKey }
  });
  return readPrefix(setting?.value);
}

export async function saveParticipantReferencePrefix(prefix: string) {
  const normalizedPrefix = prefix.trim() || defaultReferencePrefix;
  const existing = await prisma.systemSetting.findFirst({
    where: { conferenceId: null, key: referenceSettingKey }
  });

  if (existing) {
    await prisma.systemSetting.update({
      where: { id: existing.id },
      data: { value: { prefix: normalizedPrefix } }
    });
  } else {
    await prisma.systemSetting.create({
      data: { key: referenceSettingKey, value: { prefix: normalizedPrefix } }
    });
  }

  return normalizedPrefix;
}

export async function generateParticipantReference(prefix?: string) {
  const activePrefix = prefix ?? await getParticipantReferencePrefix();
  const latest = await prisma.participantProfile.findFirst({
    where: { registrationReference: { startsWith: `${activePrefix}-` } },
    orderBy: { registrationReference: "desc" },
    select: { registrationReference: true }
  });

  const latestNumber = Number(latest?.registrationReference.split("-").at(-1) ?? "0");
  const nextNumber = Number.isFinite(latestNumber) ? latestNumber + 1 : 1;
  return `${activePrefix}-${String(nextNumber).padStart(4, "0")}`;
}

export async function getParticipantReferenceSettings() {
  const prefix = await getParticipantReferencePrefix();
  return {
    prefix,
    nextPreview: await generateParticipantReference(prefix)
  };
}
