<?php

namespace App\Domains\Cart\Resources;

use App\Domains\Cart\Models\CartItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @mixin CartItem
 */
class CartItemResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $selectedItem = $this->selectedItem();
        $imageUrl = null;

        if ($selectedItem?->relationLoaded('attachments')) {
            $imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
        }

        if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
            $imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
        }

        return [
            'id' => $this->id,
            'cantidad' => $this->cantidad,
            'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
            'catalog_item_id' => $this->catalog_item_id,
            'variant_id' => $this->variant_id,
            'product' => $selectedItem === null ? null : [
                'nombre' => $selectedItem->getName(),
                'imagen' => $imageUrl,
            ],
        ];
    }

    protected function formatMoney(float|int|string|null $amount): string
    {
        return number_format((float) ($amount ?? 0), 2, '.', '');
    }
}
