<?php

namespace App\Transformers\Objects;

use App\Models\Objects\NirObject;
use App\Services\PermissionsService;
use App\Transformers\Pages\PageTransformer;
use App\Transformers\Users\UserTransformer;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\Primitive;
use League\Fractal\TransformerAbstract;

class ObjectTransformer extends TransformerAbstract {
    protected array $defaultIncludes = [

    ];

    protected array $availableIncludes = [
        'groups', 'type', 'owner', 'pages', 'permissions'
    ];

    public function transform(NirObject $model): array {
        return [
            'id' => $model->uuid,
            'name' => $model->name,
            'type_title' => $model->type->title ?? null,
            'pivot' => ['group' => $model->pivot->group ?? null, 'ord' => $model->pivot->ord ?? null],
            'created_at' => $model->created_at ? $model->created_at->toIso8601String() : null,
            'updated_at' => $model->updated_at ? $model->updated_at->toIso8601String() : null
        ];
    }

    public function includeGroups(NirObject $model): Collection {
        return $this->collection($model->properties, new ObjectPropertiesGroupTransformer($model));
    }

    public function includeType(NirObject $model): ?Item {
        return $model->type ? $this->item($model->type, new ObjectTypeTransformer()) : null;
    }

    public function includeOwner(NirObject $model): ?Item {
        return $model->owner ? $this->item($model->owner, new UserTransformer()) : null;
    }

    public function includePages(NirObject $model): Collection {
        return $this->collection($model->pages, new PageTransformer());
    }

    public function includePermissions(NirObject $model): Primitive {
        return $this->primitive((new PermissionsService($model))->get());
    }


}
