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

/**
 * Session information interceptor.
 *
 * This interceptor extracts the authenticated user information from the request
 * and sets it in the SessionService for the duration of the request.
 */
@Injectable()
export class SessionInfoInterceptor implements NestInterceptor {
	intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
		const request = context.switchToHttp().getRequest()

		const user = request.user as SessionInfo
		if (!user) {
			throw new NotAcceptableException('USER NOT FOUND')
		}

		SessionStore.set(user)

		return next.handle()
	}
}
