<?php

declare(strict_types=1);

namespace PortalPeople\Swiftcomplete\Model\Checkout;

use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class ConfigProvider implements ConfigProviderInterface
{
    private const XML_PATH_ENABLED = 'portalpeople_swiftcomplete/general/enabled';
    private const XML_PATH_API_KEY = 'portalpeople_swiftcomplete/general/api_key';
    private const XML_PATH_COUNTRY_CODE = 'portalpeople_swiftcomplete/general/country_code';
    private const XML_PATH_SEARCH_FOR = 'portalpeople_swiftcomplete/general/search_for';
    private const XML_PATH_PROMPT_TEXT = 'portalpeople_swiftcomplete/general/prompt_text';
    private const XML_PATH_INPUT_LABEL = 'portalpeople_swiftcomplete/general/input_label';
    private const XML_PATH_INPUT_PLACEHOLDER = 'portalpeople_swiftcomplete/general/input_placeholder';

    private const DEFAULT_COUNTRY_CODE = 'gb';
    private const DEFAULT_SEARCH_FOR = 'what3words,address';
    private const DEFAULT_PROMPT_TEXT = 'Type your address, postcode, or what3words';
    private const DEFAULT_INPUT_LABEL = 'Address lookup';
    private const DEFAULT_INPUT_PLACEHOLDER = 'Start typing your address, postcode, or what3words';

    private ScopeConfigInterface $scopeConfig;

    public function __construct(ScopeConfigInterface $scopeConfig)
    {
        $this->scopeConfig = $scopeConfig;
    }

    public function getConfig(): array
    {
        $apiKey = trim($this->getValue(self::XML_PATH_API_KEY));

        return [
            'portalpeopleSwiftcomplete' => [
                'enabled' => $this->isEnabled() && $apiKey !== '',
                'apiKey' => $apiKey,
                'countryCode' => $this->getValue(self::XML_PATH_COUNTRY_CODE, self::DEFAULT_COUNTRY_CODE),
                'searchFor' => $this->getValue(self::XML_PATH_SEARCH_FOR, self::DEFAULT_SEARCH_FOR),
                'promptText' => $this->getValue(self::XML_PATH_PROMPT_TEXT, self::DEFAULT_PROMPT_TEXT),
                'inputLabel' => $this->getValue(self::XML_PATH_INPUT_LABEL, self::DEFAULT_INPUT_LABEL),
                'inputPlaceholder' => $this->getValue(
                    self::XML_PATH_INPUT_PLACEHOLDER,
                    self::DEFAULT_INPUT_PLACEHOLDER
                ),
                'scriptUrl' => 'https://assets.swiftcomplete.com/js/swiftlookup.js',
            ],
        ];
    }

    private function isEnabled(): bool
    {
        return $this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE);
    }

    private function getValue(string $path, string $default = ''): string
    {
        $value = (string) $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE);

        return $value !== '' ? $value : $default;
    }
}
