<?php

namespace App\Domains\Cart\Resources;

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

/**
 * @mixin Cart
 */
class CartResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $items = $this->resource->relationLoaded('items')
            ? $this->resource->getRelation('items')
            : collect();

        $subtotal = $items->reduce(
            fn (float $carry, $item): float => $carry
                + ((float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad),
            0.0,
        );

        return [
            'id' => $this->id,
            'tenant_codigo' => $this->tenant_codigo,
            'status' => $this->status ?? 'active',
            'items' => CartItemResource::collection($items),
            'subtotal' => $this->formatMoney($subtotal),
        ];
    }

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