import {
    Injectable,
    NestInterceptor,
    ExecutionContext,
    CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { i18nStore } from './i18n.store';
import { DEFAULT_LANGUAGE } from '../common/constants';

@Injectable()
export class I18nInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const request = context.switchToHttp().getRequest();
        const language = request.headers['x-user-language'] || DEFAULT_LANGUAGE;

        return new Observable((observer) => {
            i18nStore.run({ language: String(language) }, () => {
                next.handle().subscribe({
                    next: (value) => observer.next(value),
                    error: (err) => observer.error(err),
                    complete: () => observer.complete(),
                });
            });
        });
    }
}
