<?php

namespace App\Http\Resources;

use App\Events\LoadFranchiseDataFields;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Http\Resources\MediaEntryResource;
use Mtc\MercuryDataModels\Enums\SocialMediaPlatform;
use Mtc\MercuryDataModels\VehicleMake;

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

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $this->resource->load('mediaUses.media');
        $this->loadDataFields();
        $this->resource->ensureSocialsHasAllPlatforms();
        $resource = $this->resource->toArray();
        $resource['media'] = $this->resource->mediaUses
            ->filter(fn ($mediaUse) => $mediaUse->primary ?? null)
            ->values()
            ->pluck('media_id');
        $resource['media_uses'] = $this->resource->mediaUses
            ->filter(fn ($mediaUse) => $mediaUse->primary ?? null)
            ->values()
            ->map(fn(MediaUse $mediaUse) => new MediaEntryResource($mediaUse));

        $resource['square_logo'] = $this->resource->mediaUses
            ->filter(fn ($mediaUse) => $mediaUse->flags['square'] ?? null)
            ->values()
            ->pluck('media_id');
        $resource['square_logo_uses'] = $this->resource->mediaUses
            ->filter(fn ($mediaUse) => $mediaUse->flags['square'] ?? null)
            ->values()
            ->map(fn(MediaUse $mediaUse) => new MediaEntryResource($mediaUse));

        return [
            'franchise' => $resource,
            'makes' => VehicleMake::query()->select(['id', 'name'])->get(),
            'social_media_platforms' => collect(SocialMediaPlatform::cases())->map(fn ($p) => [
                'key' => $p->value,
                'label' => $p->label(),
            ]),
        ];
    }

    private function loadDataFields()
    {
        $this->resource->data_fields = collect(event(new LoadFranchiseDataFields()))
            ->filter()
            ->mapWithKeys(fn($field) => $field)
            ->map(function ($field, $key) {
                $field['id'] = $key;
                return $field;
            })->values();

        $this->ensureDataHasFields();
    }

    private function ensureDataHasFields()
    {
        $data = $this->resource->data ?? [];

        foreach ($this->resource->data_fields as $field) {
            if (!isset($data[$field['id']])) {
                $data[$field['id']] = ($field['type'] === 'checkbox') ? false : '';
            }
        }

        $this->resource->data = $data;
    }
}
