import type { PrismaClient, ReferenceDomain } from '@prisma/client';

/**
 * Reference values are one table serving many lists, so an id on its own proves
 * nothing: a lease type, a property category and a maintenance priority are the
 * same shape and the same cuid space. Every field that stores one resolves it
 * through here first, so a wrong-list (or another org's) id is refused instead
 * of being written and read back as a blank name.
 *
 * Deliberately not filtered on isActive: re-saving an old record whose value has
 * since been retired must not fail — retiring one stops it being OFFERED, it
 * does not invalidate what already refers to it.
 */
export async function findReferenceValue(
  prisma: PrismaClient,
  organizationId: string | undefined,
  domain: ReferenceDomain,
  id: string,
): Promise<{ id: string } | null> {
  return prisma.referenceValue.findFirst({ where: { id, organizationId, domain }, select: { id: true } });
}

/** The option list a picker offers for one of those lists: active only, in the
 *  order the office arranged them. */
export async function referenceOptions(
  prisma: PrismaClient,
  organizationId: string | undefined,
  domain: ReferenceDomain,
): Promise<{ id: string; code: string; nameEn: string; nameZh: string | null }[]> {
  return prisma.referenceValue.findMany({
    where: { organizationId, domain, isActive: true },
    orderBy: [{ sortOrder: 'asc' }, { nameEn: 'asc' }],
    select: { id: true, code: true, nameEn: true, nameZh: true },
  });
}
