<?php

namespace App\Domains\Purchase\Resources;

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

/**
 * @mixin \App\Domains\Purchase\Models\PurchaseItem
 */
class PurchaseItemResource 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($this->precio_unitario),
            'total' => $this->formatMoney($this->total),
            '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
    {
        if ($amount === null) {
            return null;
        }

        return number_format((float) $amount, 2, '.', '');
    }
}
