<?php

namespace App\Http\Controllers\Api\V1\Banner\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class BannerResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->whenHas('id'),
            'app' => $this->whenHas('app'),
            'title' => $this->whenHas('title'),
            'place' => $this->whenHas('place'),
            'link' => $this->whenHas('link'),
            'resource_type' => $this->whenHas('resource_type'),
            'resource_id' => $this->whenHas('resource_id'),
            'thumbnail' => $this->thumbnail('350x350'),
            'related_resources' => $this->when(
                condition: $this->shouldIncludeRelatedResources($request),
                value: fn () => $this->relatedResources(),
            ),
        ];
    }

    /**
     * Check if should include related resources
     */
    protected function shouldIncludeRelatedResources(Request $request): bool
    {
        if (! $request->fields) {
            $request->merge(['fields' => ['*']]);
        }

        if ($request->fields[0] === '*') {
            return true;
        }

        return in_array(['resource_type', 'resource_id', 'place'], $request->fields);
    }
}
