import { Request, Response, NextFunction } from 'express';
import type { TenantKind } from '@prisma/client';
import { prismaUnscoped } from '../lib/prisma';
import { hasFeature, type FeatureKey } from '../lib/tenant-features';
import { ForbiddenError, UnauthorizedError } from '../lib/errors';

/**
 * Refuse the request unless the caller's tenant kind has `key` switched on
 * (lib/tenant-features). The apps hide switched-off modules; this is what
 * makes the switch real for anyone calling the API directly.
 *
 * The kind is read once a minute per tenant: it changes only when the super
 * admin edits the tenant, and a minute's lag there is harmless.
 */
const TTL_MS = 60_000;
const kindCache = new Map<string, { kind: TenantKind; at: number }>();

export async function tenantKindOf(tenantId: string): Promise<TenantKind | null> {
  const hit = kindCache.get(tenantId);
  if (hit && Date.now() - hit.at < TTL_MS) return hit.kind;
  const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { kind: true } });
  if (!tenant) return null;
  kindCache.set(tenantId, { kind: tenant.kind, at: Date.now() });
  return tenant.kind;
}

/** True when the tenant's kind has the feature. For background jobs that have no request. */
export async function tenantHasFeature(tenantId: string, key: FeatureKey): Promise<boolean> {
  const kind = await tenantKindOf(tenantId);
  return !!kind && hasFeature(kind, key);
}

export function requireFeature(key: FeatureKey) {
  return (req: Request, _res: Response, next: NextFunction): void => {
    if (!req.user) throw new UnauthorizedError();
    const tenantId = req.user.tenantId;
    if (!tenantId) throw new ForbiddenError('This needs a hostel account', 'FEATURE_OFF');
    tenantHasFeature(tenantId, key)
      .then((on) => {
        if (!on) throw new ForbiddenError('This module is not switched on for your account', 'FEATURE_OFF');
        next();
      })
      .catch(next);
  };
}
