<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\LengthAwarePaginator;
use Mtc\MercuryDataModels\Property;

class PropertyList extends JsonResource
{
    public static $wrap = '';

    private string $categoryName = '';

    public function setCategoryName(string $name): self
    {
        $this->categoryName = $name;
        return $this;
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $viewColumns = $this->getViewColumns($this->resource);
            $this->resource
                ->through(fn(Property $vehicle) => $this->mapProperty($vehicle));
        } else {
            $this->resource = $this->resource
                ->map(fn(Property $vehicle) => $this->mapProperty($vehicle));
            return parent::toArray($request);
        }

        $resource = $this->resource->toArray();
        $resource['category'] = $this->categoryName;
        $resource['view_columns'] = $viewColumns;

        return $resource;
    }

    /**
     * Convert property to the json format used in lists
     *
     * @param Property $property
     * @return array
     */
    protected function mapProperty(Property $property): array
    {
        return [
            'id' => $property->id,
            'slug' => $property->slug,
            'name' => $property->name,
            'active' => $property->active,
            'data' => $property->data,
            'order' => $property->order,
            'metaItems' => $property->attributeValues
                ->filter(fn($attribute) => $attribute->propertyField->type == 'text')
                ->mapWithKeys(fn($attribute) => [$attribute->slug => $attribute->value]),
        ];
    }

    private function getViewColumns($resource)
    {
        $fields = $resource->first()?->category?->fields()
            ->where('type', 'text')
            ->active()
            ->pluck('name', 'slug') ?? collect([]);

        return $fields
            ->map(fn($name, $slug) => [
                'id' => $slug,
                'name' => $name,
            ])
            ->values();
    }
}
