<?php

namespace App\Services\Forms\Registries;

use App\Models\Objects\NirObject;
use App\Models\Objects\ObjectType;
use App\Models\Registries\Entry;
use App\Services\Forms\FormsService;
use App\Transformers\Objects\FieldTransformer;
use App\Transformers\Objects\ObjectPropertyTransformer;
use App\Transformers\Objects\ObjectTransformer;
use Illuminate\Http\JsonResponse;

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

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

    public function commonGroupFields(Entry $entry, ?NirObject $model): array {
        $objectTypeName = $entry->registry->options['operations'] ?? null;
        return $model ? fractal($model->groups->first()->fields, new ObjectPropertyTransformer($model))->toArray() :
            fractal(ObjectType::byName($objectTypeName)->firstOrFail()->groups()->first()->fields, new FieldTransformer())->toArray();
    }



    public function store(array $data): ?JsonResponse {
        $entry = Entry::byUuid($data['entry'] ?? null)->firstOrFail();
        $model = $entry->createObject($entry->registry->options['operations'] ?? null, null, 'operations');
        $model->setValues($data);
        $entry->sortOperations();
        return fractal($model, new ObjectTransformer())->respond();
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = NirObject::byUuid($id)->firstOrFail();
        $model->setValues($data);
        $model->entries()->first()->sortOperations();
        return fractal($model->fresh(), new ObjectTransformer())->respond();
    }
}
