<?php

namespace App\Modules\Settings\Localization\DTOs;

final readonly class TranslationData
{
    public function __construct(
        public string $key,
        public string $group,
        public string $locale,
        public string $value,
    ) {}

    /**
     * @param  array{key: string, locale: string, value: string, group?: ?string}  $data
     */
    public static function fromValidated(array $data): self
    {
        $key = trim($data['key']);
        $group = $data['group'] ?? null;

        if ($group === null || $group === '') {
            $group = str_contains($key, '.')
                ? strstr($key, '.', true)
                : $key;
        }

        return new self(
            key: $key,
            group: $group,
            locale: strtolower(trim($data['locale'])),
            value: $data['value'],
        );
    }

    /**
     * @return array{key: string, group: string, locale: string, value: string}
     */
    public function toArray(): array
    {
        return [
            'key' => $this->key,
            'group' => $this->group,
            'locale' => $this->locale,
            'value' => $this->value,
        ];
    }
}
