import { SessionInfo } from '@core/types'
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, NotAcceptableException } from '@nestjs/common'
import { FastifyRequest } from 'fastify'
import { Observable } from 'rxjs'
import { SessionStore } from '../helpers'

/**
 * This interceptor extracts the tenant ID from the request headers and sets it in the SessionService.
 */
@Injectable()
export class TenantHeaderInterceptor implements NestInterceptor {
	intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
		const request = context.switchToHttp().getRequest() as FastifyRequest['raw']

		const tenantId = request.headers['X-TENANT-ID'] || request.headers['x-tenant-id']
		if (!tenantId) {
			throw new NotAcceptableException('TENANT NOT FOUND')
		}
		SessionStore.set({ tenantId } as SessionInfo)

		return next.handle()
	}
}
