import { FastifyReply } from 'fastify';
import { SpamErrorCode, HttpStatus, SpamErrorResponse } from './spamshield.config';

export { SpamErrorCode, HttpStatus };
export type { SpamErrorResponse };

/**
 * Standardized error response builder for SpamShield API
 */
export class ErrorHandler {
  /**
   * Create a standard error response
   */
  static create(
    code: SpamErrorCode,
    message: string,
    options?: {
      field?: string;
      requestId?: string;
      additionalData?: Record<string, unknown>;
    }
  ): SpamErrorResponse {
    return {
      error: {
        code,
        message,
        ...(options?.field && { field: options.field }),
        timestamp: new Date().toISOString(),
        ...(options?.requestId && { requestId: options.requestId }),
      },
    };
  }

  /**
   * Send a standard error response with appropriate HTTP status code
   */
  static send(
    reply: FastifyReply,
    code: SpamErrorCode,
    message: string,
    options?: {
      field?: string;
      status?: number;
      requestId?: string;
    }
  ): void {
    const status = options?.status ?? this.getStatusForCode(code);
    const errorResponse = this.create(code, message, {
      field: options?.field,
      requestId: options?.requestId,
    });
    reply.code(status).send(errorResponse);
  }

  /**
   * Map error codes to HTTP status codes
   */
  private static getStatusForCode(code: SpamErrorCode): number {
    const statusMap: Record<SpamErrorCode, number> = {
      // Client errors
      [SpamErrorCode.INVALID_REQUEST]: HttpStatus.BAD_REQUEST,
      [SpamErrorCode.MISSING_REQUIRED_FIELD]: HttpStatus.BAD_REQUEST,
      [SpamErrorCode.UNAUTHORIZED]: HttpStatus.UNAUTHORIZED,
      [SpamErrorCode.NOT_FOUND]: HttpStatus.NOT_FOUND,
      [SpamErrorCode.VALIDATION_ERROR]: HttpStatus.BAD_REQUEST,
      
      // Server errors
      [SpamErrorCode.CLASSIFICATION_FAILED]: HttpStatus.UNPROCESSABLE_ENTITY,
      [SpamErrorCode.REPUTATION_CHECK_FAILED]: HttpStatus.UNPROCESSABLE_ENTITY,
      [SpamErrorCode.ANALYSIS_FAILED]: HttpStatus.UNPROCESSABLE_ENTITY,
      [SpamErrorCode.FEEDBACK_RECORD_FAILED]: HttpStatus.UNPROCESSABLE_ENTITY,
      [SpamErrorCode.DATABASE_ERROR]: HttpStatus.INTERNAL_SERVER_ERROR,
      [SpamErrorCode.RATE_LIMIT_EXCEEDED]: HttpStatus.TOO_MANY_REQUESTS,
      [SpamErrorCode.SERVICE_UNAVAILABLE]: HttpStatus.SERVICE_UNAVAILABLE,
    };
    return statusMap[code] ?? HttpStatus.INTERNAL_SERVER_ERROR;
  }

  /**
   * Validate required string field
   */
  static validateRequiredField(
    value: unknown,
    fieldName: string
  ): { isValid: boolean; error?: { code: SpamErrorCode; message: string; field: string } } {
    if (!value || typeof value !== 'string' || value.trim() === '') {
      return {
        isValid: false,
        error: {
          code: SpamErrorCode.MISSING_REQUIRED_FIELD,
          message: `${fieldName} is required`,
          field: fieldName,
        },
      };
    }
    return { isValid: true };
  }

  /**
   * Validate boolean field
   */
  static validateBooleanField(
    value: unknown,
    fieldName: string
  ): { isValid: boolean; error?: { code: SpamErrorCode; message: string; field: string } } {
    if (value === undefined || value === null || typeof value !== 'boolean') {
      return {
        isValid: false,
        error: {
          code: SpamErrorCode.VALIDATION_ERROR,
          message: `${fieldName} must be a boolean`,
          field: fieldName,
        },
      };
    }
    return { isValid: true };
  }
}
