import type { Request, Response, NextFunction } from 'express'; import { prisma } from '../config/database.js'; import { AppError } from './error.middleware.js'; declare global { namespace Express { interface Request { tenantSchema?: string; } } } export async function tenantMiddleware(req: Request, res: Response, next: NextFunction) { if (!req.user) { return next(new AppError(401, 'No autenticado')); } try { const tenant = await prisma.tenant.findUnique({ where: { id: req.user.tenantId }, select: { schemaName: true, active: true }, }); if (!tenant || !tenant.active) { return next(new AppError(403, 'Tenant no encontrado o inactivo')); } req.tenantSchema = tenant.schemaName; // Set search_path for this request await prisma.$executeRawUnsafe(`SET search_path TO "${tenant.schemaName}", public`); next(); } catch (error) { next(new AppError(500, 'Error al configurar tenant')); } }