<?php

namespace App\Http\Resources;

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

class HuntResource extends JsonResource
{
    public static $wrap = null;

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $participationStatus = $this->participationStatus($request);

        return array_merge(parent::toArray($request), [
            'xp' => $this->resource->totalXp(),
            'is_participating' => $participationStatus !== null,
            'participation_status' => $participationStatus,
        ]);
    }

    /**
     * @return array<string, mixed>|null
     */
    private function participationStatus(Request $request): ?array
    {
        $user = $request->user();

        if ($user === null || ! $this->resource->relationLoaded('participants')) {
            return null;
        }

        $participant = $this->resource->participants->firstWhere('id', $user->id);

        if ($participant === null || $participant->pivot === null) {
            return null;
        }

        return [
            'user_id' => $participant->pivot->user_id,
            'hunt_id' => $participant->pivot->hunt_id,
            'current_step_number' => (int) $participant->pivot->current_step_number,
            'status' => $participant->pivot->status,
            'created_at' => $participant->pivot->created_at?->toJSON(),
            'updated_at' => $participant->pivot->updated_at?->toJSON(),
        ];
    }
}
