import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';

export interface PaginationMeta {
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export class ApiResponseDto<T = any> {
  @ApiProperty({ example: 200, description: 'HTTP 状态码' })
  statusCode: number;

  @ApiProperty({ example: '操作成功', description: '响应消息' })
  message: string;

  @ApiProperty({ description: '响应数据' })
  data?: T;

  @ApiPropertyOptional({ description: '分页信息' })
  meta?: PaginationMeta;

  @ApiProperty({ example: true, description: '请求是否成功' })
  success: boolean;

  @ApiProperty({ example: '2024-01-01T00:00:00.000Z', description: '响应时间戳' })
  timestamp: string;

  constructor(params: {
    statusCode: number;
    message: string;
    data?: T;
    meta?: PaginationMeta;
  }) {
    this.statusCode = params.statusCode;
    this.message = params.message;
    this.data = params.data;
    this.meta = params.meta;
    this.success = params.statusCode >= 200 && params.statusCode < 300;
    this.timestamp = new Date().toISOString();
  }

  static success<T>(data: T, message = '操作成功', statusCode = 200): ApiResponseDto<T> {
    return new ApiResponseDto({
      statusCode,
      message,
      data,
    });
  }

  static error(message: string, statusCode = 400): ApiResponseDto<null> {
    return new ApiResponseDto({
      statusCode,
      message,
      data: null,
    });
  }

  static paginated<T>(
    data: T[],
    page: number,
    pageSize: number,
    total: number,
    message = '获取成功'
  ): ApiResponseDto<T[]> {
    return new ApiResponseDto({
      statusCode: 200,
      message,
      data,
      meta: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize),
      },
    });
  }
}

export class ApiErrorResponseDto {
  @ApiProperty({ example: 400, description: 'HTTP 状态码' })
  statusCode: number;

  @ApiProperty({ example: '请求参数错误', description: '错误信息' })
  message: string;

  @ApiProperty({ example: false, description: '请求是否成功' })
  success: boolean;

  @ApiProperty({ example: '2024-01-01T00:00:00.000Z', description: '响应时间戳' })
  timestamp: string;

  @ApiPropertyOptional({ example: { field: ['错误详情'] }, description: '详细错误信息' })
  errors?: any;

  constructor(params: {
    statusCode: number;
    message: string;
    errors?: any;
  }) {
    this.statusCode = params.statusCode;
    this.message = params.message;
    this.errors = params.errors;
    this.success = false;
    this.timestamp = new Date().toISOString();
  }
}