import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { ForbiddenError } from '../../lib/errors';

/**
 * Plan ceilings, checked at the point of creation.
 *
 * A plan is sold by properties and beds (5 Oct 2026). Rooms and students
 * are no longer capped: a room is only as big as its beds, and a dormitory
 * turns the same bed over many times, so beds are what a plan really sizes.
 *
 * Counts are tenant-wide, not per-property: the plan is sold to the tenant.
 * They come from the scoped client, so the tenant filter cannot be forgotten.
 */

export type PlanResource = 'properties' | 'beds';

const RESOURCES: Record<PlanResource, { field: 'maxProperties' | 'maxBeds'; one: string; many: string }> = {
  properties: { field: 'maxProperties', one: 'property', many: 'properties' },
  beds: { field: 'maxBeds', one: 'bed', many: 'beds' },
};

async function currentCount(resource: PlanResource): Promise<number> {
  if (resource === 'properties') return db.property.count({});
  return db.bed.count({ where: { archivedAt: null, room: { floor: { not: null } } } });
}

/**
 * Throw if creating `adding` more of `resource` would exceed the tenant's plan.
 *
 * A null limit on the plan means unlimited, and a tenant with no plan at all is
 * unrestricted — existing tenants predate plans and must not be locked out of
 * their own data by a migration. Adding zero (a room with no beds) is free.
 */
export async function assertWithinPlanLimit(resource: PlanResource, adding = 1): Promise<void> {
  if (adding <= 0) return;
  const { field, one, many } = RESOURCES[resource];
  const tenant = await prismaUnscoped.tenant.findUnique({
    where: { id: getTenantIdOrThrow() },
    include: { planRef: { select: { name: true, [field]: true } } },
  });

  const max = (tenant?.planRef as Record<string, number | null> | null)?.[field] ?? null;
  if (max == null) return;

  const existing = await currentCount(resource);
  if (existing + adding <= max) return;

  const planName = tenant?.planRef?.name ?? 'current';
  const left = Math.max(0, max - existing);
  throw new ForbiddenError(
    `Your ${planName} plan allows ${max} ${max === 1 ? one : many}. You have ${existing}${left > 0 ? `, so ${left} more can be added` : ''}. Upgrade to add more.`,
    'PLAN_LIMIT_REACHED',
  );
}

/** What a tenant uses today, against which a plan's limits are checked. */
export async function tenantUsage(tenantId: string) {
  const [properties, beds] = await Promise.all([
    prismaUnscoped.property.count({ where: { tenantId } }),
    prismaUnscoped.bed.count({ where: { tenantId, archivedAt: null, room: { floor: { not: null } } } }),
  ]);
  return { properties, beds };
}

/**
 * Why a plan cannot hold a tenant as it stands, or null when it can. Moving a
 * tenant onto a plan smaller than what they already have would leave them
 * over the limit from day one.
 */
export function planShortfall(plan: { maxProperties: number | null; maxBeds: number | null }, usage: { properties: number; beds: number }): string | null {
  const over: string[] = [];
  if (plan.maxProperties != null && usage.properties > plan.maxProperties) over.push(`${usage.properties} properties (plan allows ${plan.maxProperties})`);
  if (plan.maxBeds != null && usage.beds > plan.maxBeds) over.push(`${usage.beds} beds (plan allows ${plan.maxBeds})`);
  return over.length ? over.join(' and ') : null;
}
