import { Request, Response, NextFunction } from 'express';
import { Role } from '@prisma/client';
import { verifyAccessToken } from '../lib/jwt';
import { ForbiddenError, UnauthorizedError } from '../lib/errors';
import { runWithTenantContext } from '../lib/tenantContext';
import { effectivePermissions } from '../lib/permissions';
import { prismaUnscoped } from '../lib/prisma';
import { keepMoneyOutOfEnterprise } from './enterpriseNoMoney';

/**
 * Verify the Bearer access token, compute the user's effective permissions
 * (loading an assigned custom role for staff), attach `req.user`, and bind the
 * tenant context so the scoped Prisma client auto-filters.
 */
/**
 * Platform team accounts belong to no hostel. Each is fenced to its own area
 * and its own account here, once, so a hostel route that only checks for a
 * session can never run a tenant query for them — today's or one added later.
 */
const FENCED: Partial<Record<Role, { prefixes: string[]; message: string }>> = {
  [Role.CRM_USER]: { prefixes: ['/api/crm', '/api/auth'], message: 'CRM accounts can only use the CRM.' },
  [Role.CONTENT_EDITOR]: { prefixes: ['/api/blog-cms', '/api/auth'], message: 'Blog accounts can only use the blog.' },
  [Role.QA]: { prefixes: ['/api/bug-tracker', '/api/auth'], message: 'Bug tracker accounts can only use the bug tracker.' },
  [Role.DEVELOPER]: { prefixes: ['/api/bug-tracker', '/api/auth'], message: 'Bug tracker accounts can only use the bug tracker.' },
};

export function authenticate(req: Request, res: Response, next: NextFunction): void {
  authImpl(req, res, next).catch(next);
}

async function authImpl(req: Request, res: Response, next: NextFunction): Promise<void> {
  const header = req.header('authorization');
  if (!header?.startsWith('Bearer ')) {
    throw new UnauthorizedError('Missing Bearer token');
  }
  const payload = verifyAccessToken(header.slice('Bearer '.length).trim());

  const fence = FENCED[payload.role];
  if (fence) {
    const path = req.originalUrl.split('?')[0];
    if (!fence.prefixes.some((p) => path === p || path.startsWith(`${p}/`))) {
      throw new ForbiddenError(fence.message);
    }
  }

  // Staff may carry a custom role that overrides their default permissions.
  let customRolePerms: string[] | null = null;
  if (payload.role === Role.WARDEN || payload.role === Role.MESS_ADMIN) {
    const user = await prismaUnscoped.user.findUnique({
      where: { id: payload.sub },
      include: { customRole: { select: { permissions: true } } },
    });
    customRolePerms = user?.customRole?.permissions ?? null;
  }

  req.user = { ...payload, perms: effectivePermissions(payload.role, customRolePerms) };
  await keepMoneyOutOfEnterprise(req, res);

  runWithTenantContext({ userId: payload.sub, role: payload.role, tenantId: payload.tenantId }, () => next());
}
