<?php

namespace App\Transformers\Publications;

use App\Models\Asset;
use App\Models\Publications\Publication;
use App\Models\Publications\PublicationType;
use App\Services\PermissionsService;
use App\Transformers\Assets\AssetTransformer;
use App\Transformers\Objects\ObjectTransformer;
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 PublicationTransformer extends TransformerAbstract {
    protected array $defaultIncludes = [
    ];

    protected array $availableIncludes = [
        'page', 'parents', 'posters', 'author', 'sections', 'sidebars', 'permissions'
    ];

    public function transform(Publication $model): array {
        return [
            'id' => $model->uuid,
            'slug' => $model->slug,
            'link' => $model->link,
            'type' => ['name' => 'publication', 'title' => 'Публикация'],
            'name' => $model->name,
            'excerpt' => $model->excerpt,
            'content' => $model->content,
            'publish_date_rus' => $model->publish_date_rus,
            'is_published' => boolval($model->is_published),
            'is_blank' => boolval($model->is_blank),
            'published_at' => $model->published_at ? $model->published_at->toIso8601String() : null,
            'created_at' => $model->created_at ? $model->created_at->toIso8601String() : null,
            'updated_at' => $model->updated_at ? $model->updated_at->toIso8601String() : null
        ];
    }

    public function includePage(Publication $model): ?Item {
        return $model->page ? $this->item($model->page, new PageTransformer()) : null;
    }

    public function includeParents(Publication $model): Collection {
        return $this->collection($model->parents->reverse(), new PageTransformer());
    }

    public function includePosters(Publication $model): Collection {
        return $this->collection($model->images, new AssetTransformer());
    }

    public function includeAuthor(Publication $model): ?Item {
        return $model->author ? $this->item($model->author, new UserTransformer()) : null;
    }

    public function includeSections(Publication $model): Collection {
        return $this->collection($model->sections, new ObjectTransformer());
    }

    public function includeSidebars(Publication $model): Collection {
        return $this->collection($model->sidebars, new ObjectTransformer());
    }

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


}
