<?php

namespace App\Services\Forms\Registries;

use App\Models\Objects\FieldType;
use App\Models\Registries\Category;
use App\Models\Registries\Registry;
use App\Services\Forms\FormsService;
use App\Transformers\Registries\CategoryTransformer;
use Illuminate\Http\JsonResponse;

class CategoryForms extends FormsService {
    public array $formTitles = ['create' => 'Создание категории', 'update' => 'Редактирование категории'];

    public function form(?string $id = null, array $data = []): array {
        $model = Category::byUuid($id)->first();
        $groups = [
            ['name' => 'common', 'fields' => $this->commonGroupFields($model)]
        ];
        return ['title' => $this->formTitle($model), 'data' => $groups];
    }

    public function commonGroupFields(?Category $model): array {
        $fields = [
            [
                'name' => 'name',
                'title' => 'Название категории',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->name ?? null
            ]
        ];
        return ['data' => $fields];
    }



    public function store(array $data): ?JsonResponse {
        $registry = Registry::byUuid($data['registry'] ?? null)->firstOrFail();
        $parent = Category::byUuid($data['parent'] ?? null)->first();
        $data['parent_id'] = $parent->id ?? 0;
        $model = $registry->categories()->create($data);
        return fractal($model, new CategoryTransformer())->respond();
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = Category::byUuid($id)->firstOrFail();
        $model->update($data);
        return fractal($model->fresh(), new CategoryTransformer())->respond();
    }
}
