<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\StoreProductTarget;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @mixin StoreProductTarget
 */
class StorePriceResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        /** @var StoreProductTarget $target */
        $target = $this->resource;
        $obs = $target->latestObservation;
        $store = $target->store;

        $isStale = $obs !== null ? ! $obs->observed_at->isToday() : null;

        $storeProductUrl = $target->store_product_url;
        $externalUrlType = $storeProductUrl !== null ? 'store_product' : null;

        return [
            'store_id' => $store->id,
            'store_slug' => $store->slug,
            'store_name' => $store->name,
            'store_logo_url' => $store->logo_url !== null ? url($store->logo_url) : null,
            'price' => $obs?->price !== null ? number_format((float) $obs->price, 2, '.', '') : null,
            'currency' => $obs?->currency,
            'checked_at' => $obs?->observed_at,
            'is_price_stale' => $isStale,
            'observation_id' => $obs?->id,
            'product_title_detected' => $obs?->detected_title,
            'seller_detected' => $obs?->detected_seller,
            'external_url' => $storeProductUrl,
            'external_url_type' => $externalUrlType,
        ];
    }
}
