<?php

namespace App\Domains\Cart\Resources;

use App\Domains\Catalog\Resources\ProductVariantDefinitionResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @mixin \App\Domains\Cart\Models\CartItem
 */
class CartItemResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $variant = $this->variant;
        $product = $variant?->product;

        return [
            'id' => $this->id,
            'cantidad' => $this->cantidad,
            'precio_unitario' => $this->formatMoney($variant?->precio),
            'subtotal' => $this->formatMoney(($variant?->precio ?? 0) * $this->cantidad),
            'product' => $product === null ? null : [
                'id' => $product->id,
                'nombre' => $product->nombre,
                'slug' => $product->slug,
            ],
            'variant' => $variant === null ? null : [
                'id' => $variant->id,
                'nombre' => $variant->nombre,
                'slug' => $variant->slug,
                'definitions' => ProductVariantDefinitionResource::collection($variant->definitions),
            ],
        ];
    }

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