<?php

declare(strict_types=1);

namespace Autogedal\Labels\Model\Attribute;

use Magento\Catalog\Model\Config as CatalogConfig;
use Magento\Catalog\Model\Product;

class ValueOptionsProvider
{
    private CatalogConfig $catalogConfig;

    public function __construct(CatalogConfig $catalogConfig)
    {
        $this->catalogConfig = $catalogConfig;
    }

    /**
     * Resolve attribute metadata and selectable values for the admin form.
     *
     * @return array{
     *     exists: bool,
     *     frontend_input: string,
     *     mode: string,
     *     multiple: bool,
     *     options: array<int, array{label:string,value:string}>
     * }
     */
    public function get(string $attributeCode): array
    {
        $attributeCode = trim($attributeCode);
        if ($attributeCode === '') {
            return $this->emptyResult();
        }

        $attribute = $this->catalogConfig->getAttribute(Product::ENTITY, $attributeCode);
        if (!$attribute || !$attribute->getId()) {
            return $this->emptyResult();
        }

        $frontendInput = (string)$attribute->getFrontendInput();
        $multiple = $frontendInput === 'multiselect';
        $mode = 'input';
        $options = [];

        if (in_array($frontendInput, ['select', 'boolean', 'multiselect'], true) && $attribute->usesSource()) {
            $mode = $multiple ? 'multiselect' : 'select';
            foreach ($attribute->getSource()->getAllOptions(false) as $option) {
                $value = (string)($option['value'] ?? '');
                $label = (string)($option['label'] ?? '');

                if ($value === '' && $label === '') {
                    continue;
                }

                $options[] = [
                    'label' => $label,
                    'value' => $value,
                ];
            }
        }

        return [
            'exists' => true,
            'frontend_input' => $frontendInput,
            'mode' => $mode,
            'multiple' => $multiple,
            'options' => $options,
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public function emptyResult(): array
    {
        return [
            'exists' => false,
            'frontend_input' => '',
            'mode' => 'input',
            'multiple' => false,
            'options' => [],
        ];
    }
}
