<?php

namespace App\Modules\ServiceBooking\Http\Resources;

use App\Traits\FormatAsCurrency;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\ServicePackage;

class ListServicePackages extends JsonResource
{
    use FormatAsCurrency;

    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $resource = $this->resource
                ->through(fn(ServicePackage $package) => $this->map($package))
                ->toArray();
            $resource['default_columns'] = [
                'price',
                'updated',
            ];
            return $resource;
        }
        $this->resource = $this->resource->map(fn(ServicePackage $package) => $this->map($package));
        return parent::toArray($request);
    }

    /**
     * Map Menu entry
     *
     * @param Menu $package
     * @return array
     */
    private function map(ServicePackage $package)
    {
        return [
            'id' => $package->id,
            'title' => $package->name,
            'description' => $package->description,
            'disallow_delete' => $package->meta['disallow_delete'] ?? false,
            'metaItems' => [
                'price' => $package->price ? $this->asCurrency($package->price) : '',
                'updated' => $package->updated_at->diffForHumans(),
            ],
        ];
    }
}
