import { Request, Response, NextFunction } from 'express';
import { db } from '../lib/prisma';
import { ForbiddenError } from '../lib/errors';

/**
 * Resolves the "active property" for a request from the `X-Property-Id` header
 * (set by the frontend's property switcher) and exposes it as `req.propertyId`.
 *
 * The id is validated through the tenant-SCOPED client, so a header naming
 * another tenant's property simply doesn't resolve — cross-tenant access is
 * impossible even if the header is forged.
 *
 * When the header is absent, `req.propertyId` is undefined and handlers fall
 * back to tenant-wide behaviour (which is what single-property tenants want).
 */
export function propertyContext(req: Request, _res: Response, next: NextFunction): void {
  const header = req.header('x-property-id');
  if (!header) return next();

  db.property
    .findFirst({ where: { id: header }, select: { id: true } })
    .then((property) => {
      if (!property) throw new ForbiddenError('Unknown property for this tenant', 'BAD_PROPERTY');
      req.propertyId = property.id;
      next();
    })
    .catch(next);
}
