<?php

namespace App\Http\Resources;

use App\Modules\Valuation\ConditionPriceTier;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\VehicleValuation\Models\VehicleValuation;

class ValuationList extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource
                ->through(fn (VehicleValuation $valuation) => $this->mapRecod($valuation));
        } else {
            $this->resource = $this->resource
                ->map(fn (VehicleValuation $valuation) => $this->mapRecod($valuation));
        }
        return parent::toArray($request);
    }
    /**
     * Convert vehicle to the json format used in lists
     *
     * @param VehicleValuation $valuation
     * @return array
     */
    protected function mapRecod(VehicleValuation $valuation)
    {
        return [
            'name' => $valuation->registration,
            'description' => $valuation->make . ' ' . $valuation->model,
            'metaItems' => [
                number_format($valuation->mileage),
                "&pound;" . number_format($this->resolveDisplayPrice($valuation)),
                $valuation->created_at->format('d/m/Y H:i'),
            ],
            'link' => '/manage-content/valuations/view/' . $valuation->id,
            'id' => $valuation->id,
        ];
    }

    /**
     * Resolve the price to show in the list, honouring the captured cosmetic
     * condition. Valuations stored against a clean or below-average condition
     * populate the matching tier column while leaving average/retail empty, so
     * we resolve the condition-matched tier first and fall back across the
     * remaining tiers to ensure a figure is always shown.
     *
     * @param VehicleValuation $valuation
     * @return float
     */
    protected function resolveDisplayPrice(VehicleValuation $valuation): float
    {
        $conditionTier = ConditionPriceTier::fromCondition($valuation->cosmetic_condition);

        return ($conditionTier ? $valuation->{$conditionTier} : null)
            ?? $valuation->average_price
            ?? $valuation->retail_price
            ?? $valuation->clean_price
            ?? $valuation->below_price
            ?? 0;
    }
}
