<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Pagination\LengthAwarePaginator;

class VehicleContentCollection extends ResourceCollection
{
    public static $wrap = null;

    private string $contentType;
    private ?LengthAwarePaginator $paginator;

    public function __construct($resource, string $contentType)
    {
        $this->paginator = $resource instanceof LengthAwarePaginator ? $resource : null;
        parent::__construct($resource);
        $this->contentType = $contentType;
    }

    public function toArray($request): array
    {
        $response = [
            'data' => $this->formatData()
        ];

        if ($this->paginator) {
            $response['pagination'] = $this->buildPagination();
        }

        return $response;
    }

    private function formatData(): array
    {
        return $this->collection->map(function ($item) {
            $data = [
                'slug' => $item['slug'],
                'title' => $item['title'],
                'thumbnail' => $item['thumbnail'],
            ];

            if ($this->contentType === 'videos') {
                $data['video_url'] = $item['video_url'];
            } else {
                $data['review'] = $item['review'];
            }

            return $data;
        })->toArray();
    }


    private function buildPagination(): array
    {
        return [
            'current_page' => $this->paginator->currentPage(),
            'last_page' => $this->paginator->lastPage(),
            'per_page' => $this->paginator->perPage(),
            'total' => $this->paginator->total(),
            'first_page_url' => $this->paginator->url(1),
            'last_page_url' => $this->paginator->url($this->paginator->lastPage()),
            'next_page_url' => $this->paginator->nextPageUrl(),
            'prev_page_url' => $this->paginator->previousPageUrl(),
        ];
    }
}
