<?php

namespace App\Domains\Catalog\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @mixin \App\Domains\Catalog\Models\ProductVariant
 */
class ProductVariantResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'producto_id' => $this->producto_id,
            'slug' => $this->slug,
            'nombre' => $this->nombre,
            'stock' => $this->stock,
            'descripcion' => $this->descripcion,
            'precio' => $this->precio,
            'product' => ProductResource::make($this->whenLoaded('product')),
            'definitions' => ProductVariantDefinitionResource::collection($this->whenLoaded('definitions')),
            'images' => $this->whenLoaded('attachments', function () {
                if ($this->attachments->isNotEmpty()) {
                    return $this->attachments
                        ->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
                        ->values();
                }

                // Fallback: use product-level attachments when the variant has none
                $this->loadMissing('product.attachments');

                return $this->product?->attachments
                    ?->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
                    ?->values()
                    ?? collect();
            }),
        ];
    }
}
