import {
	ExceptionFilter,
	Catch,
	ArgumentsHost,
	HttpException,
	HttpStatus,
	Logger,
} from '@nestjs/common';
import { Response, Request } from 'express';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
	private readonly logger = new Logger(HttpExceptionFilter.name);

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

		let status = HttpStatus.INTERNAL_SERVER_ERROR;
		let message = 'Internal server error';
		let error = 'Internal Server Error';

		if (exception instanceof HttpException) {
			status = exception.getStatus();
			const exceptionResponse = exception.getResponse();

			if (typeof exceptionResponse === 'string') {
				message = exceptionResponse;
				error = exceptionResponse;
			} else if (typeof exceptionResponse === 'object') {
				const res = exceptionResponse as Record<string, any>;
				message = res.message || message;
				error = res.error || error;
			}
		} else if (exception instanceof Error) {
			message = exception.message;
			this.logger.error(`Unhandled exception: ${exception.message}`, exception.stack);
		} else {
			this.logger.error('Unknown exception', exception);
		}

		if (status >= 500) {
			this.logger.error(
				`[${request.method}] ${request.url} - ${status}: ${message}`,
				exception instanceof Error ? exception.stack : undefined
			);
		} else {
			this.logger.warn(`[${request.method}] ${request.url} - ${status}: ${message}`);
		}

		response.status(status).json({
			statusCode: status,
			message,
			error,
			timestamp: new Date().toISOString(),
			path: request.url,
		});
	}
}
