<?php

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

use App\Nova\Resources\Ecommerce\Product\Product\Product;
use Ebess\AdvancedNovaMediaLibrary\Fields\Images;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
use Nurmuhammet\DynamicFields\DynamicFields;

class VariantFieldsForDetail
{
    /**
     * Get the fields for create.
     */
    public static function make(NovaRequest $request, $resource): array
    {
        if (! $request->isResourceDetailRequest()) {
            if ($request->viaResource && $request->viaRelationship && $request->relationshipType) {

            } else {
                return [];
            }
        }

        return [
            ID::make()->sortable(),

            BelongsTo::make(__('Parent'), 'parent', Product::class),

            Images::make(__('Image'), 'uploads')
                ->conversionOnIndexView('thumb200x200'),

            Text::make(__('Price'), 'cost_amount')
                ->rules('required', 'numeric'),

            Text::make('SKU', 'sku')
                ->rules('nullable', 'string', 'max:255'),

            Number::make(__('Stock'), 'stock')
                ->rules('required', 'integer'),

            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();
                }),
        ];
    }
}
