<?php

namespace AIPT\Api\Chatbot\Exceptions;

/**
 * Exception for service unavailable errors (HTTP 500, 502, 503, 504).
 *
 * Thrown when AI provider service is down or experiencing issues.
 * This error is potentially recoverable via retry.
 *
 * Supports multiple HTTP status codes:
 * - 500: Internal Server Error
 * - 502: Bad Gateway
 * - 503: Service Unavailable (default)
 * - 504: Gateway Timeout
 *
 * @package AIPT\Api\Chatbot\Exceptions
 * @since 2.5.0
 */
class ServiceUnavailableException extends ChatbotException {

    /**
     * Valid HTTP status codes for service unavailable errors.
     */
    private const VALID_HTTP_STATUSES = [ 500, 502, 503, 504 ];

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

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

    /**
     * HTTP status code (500, 502, 503, or 504).
     *
     * @var int
     */
    protected $http_status = 503;

    /**
     * AI provider name.
     *
     * @var string
     */
    protected $provider = '';

    /**
     * Constructor.
     *
     * @param string          $message     Error message.
     * @param string          $provider    AI provider name.
     * @param int             $code        Exception code.
     * @param \Throwable|null $previous    Previous exception.
     * @param int             $http_status HTTP status code (500, 502, 503, or 504). Defaults to 503.
     */
    public function __construct(
        string $message = '',
        string $provider = '',
        int $code = 0,
        ?\Throwable $previous = null,
        int $http_status = 503
    ) {
        $this->provider = $provider;

        $this->http_status = in_array( $http_status, self::VALID_HTTP_STATUSES, true )
            ? $http_status
            : 503;

        parent::__construct($message ?: __('AI service is temporarily unavailable.', 'ai-product-tools'), $code, $previous);
    }

    /**
     * Get AI provider name.
     *
     * @return string
     */
    public function getProvider(): string {
        return $this->provider;
    }

    /**
     * Get user-friendly error message.
     *
     * @return string
     */
    public function getUserMessage(): string {
        return __('The AI service is temporarily unavailable. Please try again in a few moments.', 'ai-product-tools');
    }
}
