<?php

namespace App\Modules\Customization\CustomFields\DTOs;

final readonly class CustomFieldWriteData
{
    /**
     * @param  list<array{label: string, value: string}>  $options
     */
    public function __construct(
        public string $module,
        public string $entity,
        public string $name,
        public string $slug,
        public string $fieldType,
        public bool $isRequired,
        public bool $isActive,
        public ?string $validationRules,
        public ?string $placeholder,
        public ?string $helpText,
        public array $options,
        public ?int $sortOrder = null,
    ) {}

    /**
     * @param  array<string, mixed>  $data
     */
    public static function fromValidated(array $data): self
    {
        /** @var list<array{label: string, value: string}> $opts */
        $opts = [];
        foreach ($data['options'] ?? [] as $row) {
            if (! is_array($row)) {
                continue;
            }
            $label = trim((string) ($row['label'] ?? ''));
            $value = trim((string) ($row['value'] ?? ''));
            if ($label === '' && $value === '') {
                continue;
            }
            $opts[] = ['label' => $label, 'value' => $value];
        }

        return new self(
            module: (string) $data['module'],
            entity: (string) $data['entity'],
            name: (string) $data['name'],
            slug: (string) $data['slug'],
            fieldType: (string) $data['field_type'],
            isRequired: (bool) ($data['is_required'] ?? false),
            isActive: (bool) ($data['is_active'] ?? true),
            validationRules: isset($data['validation_rules']) ? (string) $data['validation_rules'] : null,
            placeholder: isset($data['placeholder']) ? (string) $data['placeholder'] : null,
            helpText: isset($data['help_text']) ? (string) $data['help_text'] : null,
            options: $opts,
            sortOrder: isset($data['sort_order']) ? (int) $data['sort_order'] : null,
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function toFieldArray(int $tenantId, ?int $userId, int $sortOrder): array
    {
        return [
            'tenant_id' => $tenantId,
            'module' => $this->module,
            'entity' => $this->entity,
            'name' => $this->name,
            'slug' => $this->slug,
            'field_type' => $this->fieldType,
            'is_required' => $this->isRequired,
            'is_active' => $this->isActive,
            'validation_rules' => $this->validationRules,
            'placeholder' => $this->placeholder,
            'help_text' => $this->helpText,
            'sort_order' => $sortOrder,
            'created_by' => $userId,
            'updated_by' => $userId,
        ];
    }
}
