import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
// import { LogsService } from '../../logs/logs.service'; // TODO: 待实现

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  // constructor(private logsService: LogsService) {} // TODO: 待实现

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

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

    const message =
      exception instanceof HttpException
        ? exception.getResponse()
        : 'Internal server error';

    const errorMessage =
      typeof message === 'string'
        ? message
        : (message as any).message || 'Error';

    const errorResponse = {
      code: status,
      message: errorMessage,
      data: null,
      timestamp: new Date().toISOString(),
      path: request.url,
    };

    // 记录错误日志（仅记录 500 及以上错误）
    // 跳过日志接口本身，避免循环记录
    if (status >= 500 && !request.url.startsWith('/logs')) {
      const user = (request as any).user;
      const userId = user?.userId || null;
      console.error(
        '[HttpExceptionFilter]',
        request.method,
        request.url,
        userId,
        exception,
      );

      // const errorContent = {
      //   status,
      //   message: errorMessage,
      //   method: request.method,
      //   url: request.url,
      //   error: exception instanceof Error ? exception.stack : String(exception),
      // };
      // 限制内容长度，避免过长（TEXT 类型最大 65KB，这里限制为 50KB）
      // const content = this.truncateContent(JSON.stringify(errorContent), 50000);

      // this.logsService
      //   .create({
      //     userId,
      //     action: `ERROR ${request.method} ${request.url}`,
      //     content,
      //     ip: request.ip || '',
      //     userAgent: request.headers['user-agent'] || '',
      //   })
      //   .catch((error) => {
      //     console.error('Failed to log error:', error);
      //   });
    }

    response.status(status).json(errorResponse);
  }

  // 截断内容，避免超过数据库字段限制
  private truncateContent(content: string, maxLength: number): string {
    if (!content || content.length <= maxLength) {
      return content;
    }
    return content.substring(0, maxLength - 50) + '\n...(内容过长，已截断)';
  }
}
