/**
 * Shared smoke helper: a landlord company for a smoke's own property.
 *
 * Smokes that run under the demo org bill, take payments and hold deposits —
 * they are not about numbering — so they must not break just because the
 * office has given its document numbers the company code (DN-WF261001). Once a
 * format carries it, a note, receipt or deposit can only be numbered for a lease
 * whose units are on a property with a landlord. So each smoke's property
 * belongs to a company of its own, coded `ZZ…` as no real company is.
 *
 * Call purgeSmokeLandlord() from the smoke's cleanup, after its property is
 * gone: it also drops the counts its numbers were drawn from, which are kept per
 * company and would otherwise pile up one set per run.
 */
import type { PrismaService } from '../src/prisma/prisma.service';

/** The company with this code, made the first time it is asked for. */
export async function smokeLandlord(prisma: PrismaService, organizationId: string, code: string): Promise<string> {
  const found = await prisma.landlord.findUnique({ where: { organizationId_code: { organizationId, code } }, select: { id: true } });
  if (found) return found.id;
  const made = await prisma.landlord.create({ data: { organizationId, code, name: `${code} Smoke Holdings Limited` }, select: { id: true } });
  return made.id;
}

/** By code alone, so a cleanup that never learnt the organisation can call it. */
export async function purgeSmokeLandlord(prisma: PrismaService, code: string): Promise<void> {
  const ids = (await prisma.landlord.findMany({ where: { code }, select: { id: true } })).map((l) => l.id);
  if (ids.length === 0) return;
  await prisma.numberCounter.deleteMany({ where: { scope: { in: ids } } });
  await prisma.landlord.deleteMany({ where: { id: { in: ids } } });
}
