<?php

namespace App\Domains\Purchase\Resources;

use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin PurchaseItem */
class PurchaseItemResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        $tenant = $request->route('tenant');
        $displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;

        $imageUrl = $displayImage
            ? $this->imageAttachment?->getTemporaryUrl(1440)
            : null;

        return [
            'id' => $this->id,
            'quantity' => (int) $this->cantidad,
            'unit_price' => $this->formatMoney($this->precio_unitario),
            'line_total' => $this->formatMoney($this->total),
            'source_catalog_item_id' => $this->source_catalog_item_id,
            'source_variant_id' => $this->source_variant_id,
            'item_details' => [
                'nombre' => $this->item_nombre,
                'descripcion' => $this->descripcion,
                'slug' => $this->slug,
                'imagen' => $imageUrl,
                'attributes' => $this->variant_attributes ?? [],
            ],
        ];
    }

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