import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponse, createSuccessResponse } from '../types/api-response.type';

/**
 * Response interceptor that wraps all successful responses
 * in the standard ApiResponse format
 */
import { I18nService, I18nContext } from 'nestjs-i18n';

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<
  T,
  ApiResponse<T>
> {
  constructor(private readonly i18n: I18nService) {}

  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ApiResponse<T>> {
    return next.handle().pipe(
      map((data: unknown) => {
        // If data is already an ApiResponse, return as-is
        if (this.isApiResponse(data)) {
          return data as ApiResponse<T>;
        }

        const request = context.switchToHttp().getRequest();

        // Determine language
        const i18nContext = I18nContext.current();
        let lang = i18nContext?.lang;

        if (!lang) {
          const acceptLanguage = request.headers['accept-language'];
          const xLang = request.headers['x-lang'];

          if (xLang) {
            lang = Array.isArray(xLang) ? xLang[0] : xLang;
          } else if (acceptLanguage) {
            lang = acceptLanguage.split(',')[0].split(';')[0].split('-')[0];
          }
        }

        lang = lang || 'en';

        const message = this.i18n.translate('common.success', {
          lang,
        });

        // Wrap in success response
        return createSuccessResponse(data as T, message);
      }),
    );
  }

  private isApiResponse(data: unknown): boolean {
    return (
      data !== null &&
      typeof data === 'object' &&
      'success' in data &&
      'status' in data &&
      'message' in data &&
      'data' in data
    );
  }
}
