<?php

/**
 * Copyright 2024-2026 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2026 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\BackOffice;

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

/**
 * Names the "empty field means keep the current key, not clear it" rule of the settings form, so
 * it cannot silently regress in a future refactor.
 *
 * Its counterpart — a rejected key never overwriting the working stored one — is enforced in
 * {@see \SimplyIn\BackOffice\ConfigurationController::persistAndSync()} by not writing any key (or
 * environment) at all on a rejected save, rather than by computing a value to write.
 */
final class EffectiveApiKey
{
    /**
     * The key to attempt authenticating with: the freshly typed one, or the selected environment's
     * stored key when the field was not actually edited.
     *
     * @param string $storedKey  the SELECTED environment's stored key
     * @param string $prefilledKey what the form rendered into the field — the stored key of the
     *                             environment that was in effect at render time. The settings
     *                             template deliberately injects it so the reveal button has
     *                             something to show, which means an untouched field posts that
     *                             value back verbatim. Without treating that as "not edited",
     *                             switching environment without retyping would validate the
     *                             PREVIOUS environment's key against the newly selected one —
     *                             blocking the switch, and on success copying a key across the
     *                             very slot boundary the per-environment storage exists to keep.
     */
    public static function toAttempt(string $submittedKey, string $storedKey, string $prefilledKey = ''): string
    {
        if ($submittedKey === '' || $submittedKey === $prefilledKey) {
            return $storedKey;
        }

        return $submittedKey;
    }
}
