<?php

namespace AIPT\Api\Chatbot\Exceptions;

/**
 * Exception for rate limit errors (HTTP 429).
 *
 * Thrown when AI provider returns rate limit exceeded error.
 * This error is recoverable - messages should be queued for retry.
 *
 * @package AIPT\Api\Chatbot\Exceptions
 * @since 2.5.0
 */
class RateLimitException extends ChatbotException {

    /**
     * Error code for client response.
     *
     * @var string
     */
    protected $error_code = 'rate_limit';

    /**
     * This error is recoverable via retry.
     *
     * @var bool
     */
    protected $recoverable = true;

    /**
     * HTTP status code.
     *
     * @var int
     */
    protected $http_status = 429;

    /**
     * Seconds until retry is allowed.
     *
     * @var int
     */
    protected $retry_after = 60;

    /**
     * Constructor.
     *
     * @param string          $message     Error message.
     * @param int             $retry_after Seconds until retry allowed.
     * @param int             $code        Exception code.
     * @param \Throwable|null $previous    Previous exception.
     */
    public function __construct(
        string $message = '',
        int $retry_after = 60,
        int $code = 0,
        ?\Throwable $previous = null
    ) {
        $this->retry_after = $retry_after;
        parent::__construct($message ?: __('Rate limit exceeded. Please wait before trying again.', 'ai-product-tools'), $code, $previous);
    }

    /**
     * Get seconds until retry is allowed.
     *
     * @return int
     */
    public function getRetryAfter(): int {
        return $this->retry_after;
    }

    /**
     * Get user-friendly error message.
     *
     * @return string
     */
    public function getUserMessage(): string {
        return __('The service is busy. Your message has been queued and will be processed shortly.', 'ai-product-tools');
    }
}
