import { NextResponse } from 'next/server'; import { prisma } from './prisma'; export type TenantContext = { tenantId: string; userId?: string; userRole?: string; }; export async function getTenantContext(request: Request): Promise { const userId = request.headers.get('x-user-id'); const tenantId = request.headers.get('x-tenant-id'); const userRole = request.headers.get('x-user-role'); if (tenantId) { const tenant = await prisma.tenant.findFirst({ where: { id: tenantId, isActive: true }, select: { id: true }, }); if (!tenant) { return NextResponse.json({ error: 'Tenant not found or inactive.' }, { status: 404 }); } return { tenantId: tenant.id, userId: userId || undefined, userRole: userRole || undefined }; } const tenantSlug = request.headers.get('x-tenant-slug'); if (tenantSlug) { const tenant = await prisma.tenant.findFirst({ where: { slug: tenantSlug, isActive: true }, select: { id: true }, }); if (!tenant) { return NextResponse.json({ error: 'Tenant not found or inactive.' }, { status: 404 }); } return { tenantId: tenant.id, userId: userId || undefined, userRole: userRole || undefined }; } return NextResponse.json( { error: 'Missing tenant context. Authentication required.' }, { status: 400 } ); } export function isApiError(value: TenantContext | NextResponse): value is NextResponse { return value instanceof NextResponse; } export function badRequest(message: string) { return NextResponse.json({ error: message }, { status: 400 }); } export function serverError(error: unknown) { const message = error instanceof Error ? error.message : 'Unexpected server error'; return NextResponse.json({ error: message }, { status: 500 }); }