import type { PrismaService } from '../prisma/prisma.service';

/** A tenancy that ran (or is running) on some units, reduced to what deciding
 *  ownership of a period of metered usage needs: who, which units, and when. */
export interface Tenancy {
  tenantId: string;
  unitIds: string[];
  start: Date;
  /** The day the tenancy actually stopped — the contracted end unless it was
   *  terminated early, which is the date billing works to everywhere else. */
  end: Date;
}

/** Every real tenancy over these units. Drafts are excluded: a lease nobody has
 *  moved into yet cannot have consumed anything, and a future renewal stored as
 *  a draft would otherwise look like it owned usage that predates it. */
export async function tenanciesForUnits(prisma: PrismaService, unitIds: string[]): Promise<Tenancy[]> {
  if (unitIds.length === 0) return [];
  const rows = await prisma.lease.findMany({
    where: { deletedAt: null, status: { not: 'DRAFT' }, units: { some: { unitId: { in: unitIds } } } },
    select: { tenantId: true, startDate: true, endDate: true, terminatedAt: true, units: { select: { unitId: true } } },
  });
  return rows.map((l) => ({
    tenantId: l.tenantId,
    unitIds: l.units.map((u) => u.unitId),
    start: l.startDate,
    end: l.terminatedAt ?? l.endDate,
  }));
}

/** Whether somebody other than `tenantId` was in any of `unitIds` on `at`.
 *
 *  A meter runs across a change of tenant without noticing one, so a reading
 *  whose period opens before this tenancy did may be measuring the previous
 *  tenant's consumption. When it was the same tenant — a renewal, most often —
 *  there is nobody to charge it to but them, so it stays billable. */
export function heldByAnotherTenant(tenancies: readonly Tenancy[], unitIds: readonly string[], at: Date, tenantId: string): boolean {
  return tenancies.some(
    (t) =>
      t.tenantId !== tenantId &&
      t.unitIds.some((u) => unitIds.includes(u)) &&
      t.start.getTime() <= at.getTime() &&
      at.getTime() <= t.end.getTime(),
  );
}
