import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const errorMsg = exception instanceof Error ? exception.message : 'Unknown error';
    const stack = exception instanceof Error ? exception.stack : '';

    if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
        const logContent = `[${new Date().toISOString()}] 500 ERROR on ${request.method} ${request.url}\nError: ${errorMsg}\nStack: ${stack}\n\n`;
        try {
            fs.appendFileSync(path.join(process.cwd(), 'GLOBAL_500_ERRORS.txt'), logContent);
        } catch (e) {
            console.error('Failed to write to GLOBAL_500_ERRORS.txt', e);
        }
    }

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: status === HttpStatus.INTERNAL_SERVER_ERROR ? 'Internal server error' : errorMsg,
    });
  }
}
