<?php

namespace App\Modules\Inventory\DTOs;

use App\Modules\Inventory\Support\InventoryAttributeType;

final class InventoryAttributeWriteData
{
    /**
     * @param  list<array{value_key: string, label: string}>  $options
     */
    public function __construct(
        public readonly string $code,
        public readonly string $name,
        public readonly InventoryAttributeType $type,
        public readonly array $options,
    ) {}

    /**
     * @param  array<string, mixed>  $validated
     */
    public static function fromValidated(array $validated): self
    {
        $rawOptions = $validated['options'] ?? [];
        $options = [];
        if (is_array($rawOptions)) {
            foreach ($rawOptions as $row) {
                if (! is_array($row)) {
                    continue;
                }
                $key = trim((string) ($row['value_key'] ?? ''));
                $label = trim((string) ($row['label'] ?? ''));
                if ($key === '' || $label === '') {
                    continue;
                }
                $options[] = ['value_key' => $key, 'label' => $label];
            }
        }

        return new self(
            code: (string) $validated['code'],
            name: (string) $validated['name'],
            type: InventoryAttributeType::from((string) $validated['type']),
            options: $options,
        );
    }

    public function requiresOptions(): bool
    {
        return in_array($this->type, [InventoryAttributeType::Select, InventoryAttributeType::MultiSelect], true);
    }
}
