/**
 * DomainExceptionFilter
 *
 * Catches any DomainException bubbling up to the HTTP boundary, translates its
 * i18nKey/i18nArgs into the caller's locale (resolved by nestjs-i18n) and
 * returns a structured JSON error response.
 *
 * Non-domain errors fall through to NestJS's default handler.
 */

import { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';
import { I18nService, I18nContext } from 'nestjs-i18n';
import { Response, Request } from 'express';
import { DomainException } from '@domain/exceptions/domain.exception';
import { DEFAULT_LOCALE, Locale, toLocale } from '@domain/value-objects/locale.vo';

@Catch(DomainException)
export class DomainExceptionFilter implements ExceptionFilter {
  constructor(private readonly i18n: I18nService<Record<string, unknown>>) {}

  catch(exception: DomainException, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const lang: Locale = toLocale(I18nContext.current()?.lang, DEFAULT_LOCALE) ?? DEFAULT_LOCALE;

    const translated = this.i18n.translate(exception.i18nKey, {
      lang,
      args: exception.i18nArgs,
      defaultValue: exception.message,
    });

    const status = exception.status || HttpStatus.BAD_REQUEST;

    response.status(status).json({
      statusCode: status,
      error: exception.name,
      message: typeof translated === 'string' ? translated : exception.message,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}
