<?php

namespace App\Nova\Resources\Ecommerce\Product\Product\Concerns\Variant;

use Laravel\Nova\Http\Requests\NovaRequest;
use Nurmuhammet\DynamicFields\DynamicFields;

class VariantFieldsForPreview
{
    /**
     * Fields For Preview
     */
    public static function make(NovaRequest $request, $resource): array
    {
        if (! $request->isResourcePreviewRequest()) {
            return [
                DynamicFields::make('Attributes', 'attributes')
                    ->fields([]),
            ];
        }

        return [
            DynamicFields::make('Attributes', 'attributes')
                ->fields(function () use ($resource) {
                    $attributes = $resource->properties()->with(['attribute.values', 'values.value'])->get()->map(fn ($property) => [
                        'label' => $property->attribute->name,
                        'name' => $property->attribute->slug,
                        'type' => $property->attribute->type,
                        'default' => $property->attribute->type === 'select'
                                        ? $property->values->first()->value?->id
                                        : $property->values->first()->product_custom_value,
                        'options' => $property->attribute->values->map(fn ($value) => [
                            'label' => $value->value,
                            'value' => $value->id,
                        ])->toArray(),
                    ]);

                    return $attributes->toArray();
                }),
        ];
    }
}
