<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Geocoding\GoogleMaps\Exception;

use InPost\International\Geocoding\Exception\GeocodingException;
use InPost\International\Geocoding\GoogleMaps\Model\GeocodingResponse;

if (!defined('_PS_VERSION_')) {
    exit;
}

class GoogleMapsException extends GeocodingException
{
    /**
     * @var string
     */
    private $statusCode;

    /**
     * @var string|null
     */
    private $errorMessage;

    public function __construct(GeocodingResponse $response)
    {
        $this->statusCode = $response->getStatus();
        $this->errorMessage = $response->getErrorMessage();

        parent::__construct($this->errorMessage ?? sprintf('Geocoding failed with status code "%s".', $this->statusCode));
    }

    final public static function create(GeocodingResponse $response): self
    {
        switch ($response->getStatus()) {
            case RequestDeniedException::STATUS:
                if (InvalidApiKeyException::ERROR_MESSAGE === trim((string) $response->getErrorMessage())) {
                    return new InvalidApiKeyException($response);
                }

                return new RequestDeniedException($response);
            case OverQueryLimitException::STATUS:
                return new OverQueryLimitException($response);
            default:
                return new self($response);
        }
    }

    public function getStatusCode(): string
    {
        return $this->statusCode;
    }

    public function getErrorMessage(): ?string
    {
        return $this->errorMessage;
    }
}
