<?php

namespace AIPT\Api\Chatbot\Exceptions;

/**
 * Exception for authentication errors (HTTP 401, 403).
 *
 * Thrown when AI provider API key is invalid or expired.
 * This error is NOT recoverable without admin intervention.
 *
 * Supports both 401 (Unauthorized) and 403 (Forbidden) status codes:
 * - 401: API key is missing or invalid
 * - 403: API key is valid but lacks required permissions
 *
 * @package AIPT\Api\Chatbot\Exceptions
 * @since 2.5.0
 */
class AuthenticationException extends ChatbotException {

    /**
     * Valid HTTP status codes for authentication errors.
     */
    private const VALID_HTTP_STATUSES = [ 401, 403 ];

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

    /**
     * This error is not recoverable without admin action.
     *
     * @var bool
     */
    protected $recoverable = false;

    /**
     * HTTP status code (401 or 403).
     *
     * @var int
     */
    protected $http_status = 401;

    /**
     * Constructor.
     *
     * @param string          $message     Error message.
     * @param int             $http_status HTTP status code (401 or 403). Defaults to 401.
     * @param int             $code        Exception code.
     * @param \Throwable|null $previous    Previous exception.
     */
    public function __construct(
        string $message = '',
        int $http_status = 401,
        int $code = 0,
        ?\Throwable $previous = null
    ) {

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

        parent::__construct($message ?: __('API authentication failed. Please contact the site administrator.', 'ai-product-tools'), $code, $previous);
    }

    /**
     * Get user-friendly error message.
     *
     * Since this is a non-recoverable authentication error, the message
     * directs users to contact admin/support rather than suggesting retry.
     *
     * @return string
     */
    public function getUserMessage(): string {
        return __('The chat service is currently unavailable due to a configuration issue. Please contact the site administrator or support for assistance.', 'ai-product-tools');
    }
}
