import { Router, Request, Response } from 'express';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { prismaUnscoped } from '../../lib/prisma';
import { FEATURE_KEYS, TENANT_KIND_LABELS, featuresFor } from '../../lib/tenant-features';

/**
 * GET /api/features — what kind of place the caller's tenant is and which
 * modules it gets. Any signed-in user; a super admin, who has no tenant,
 * sees the whole catalogue.
 */
export const featuresRouter = Router();
featuresRouter.get(
  '/',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    const tenantId = req.user!.tenantId;
    const tenant = tenantId ? await prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { kind: true } }) : null;
    const kind = tenant?.kind ?? null;
    res.json({
      kind,
      kindLabel: kind ? TENANT_KIND_LABELS[kind] : null,
      features: kind ? featuresFor(kind) : [...FEATURE_KEYS],
      catalogue: [...FEATURE_KEYS],
    });
  }),
);
