<?php

namespace App\Domains\Catalog\Requests;

use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateProductVariantRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        /** @var ProductVariant|null $productVariant */
        $productVariant = $this->route('productVariant');
        /** @var \App\Domains\Catalog\Models\Product|null $product */
        $product = $this->route('producto');

        return [
            'slug' => [
                'nullable',
                'string',
                'max:255',
                Rule::unique('productos_variantes', 'slug')
                    ->ignore($productVariant?->id)
                    ->where(fn ($query) => $query->where('producto_id', $product?->id)),
            ],
            'nombre' => ['nullable', 'string', 'max:255'],
            'stock' => ['sometimes', 'integer', 'min:0'],
            'descripcion' => ['nullable', 'string'],
            'precio' => ['required', 'numeric', 'min:0'],
            'definitions' => ['sometimes', 'array'],
            'definitions.*.attribute_id' => [
                'required',
                'integer',
                'distinct',
                Rule::exists('attribute', 'id')->where(
                    fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
                ),
                function ($attribute, $value, $fail) {
                    $productId = $this->route('producto')?->id;
                    if ($productId) {
                        $exists = \Illuminate\Support\Facades\DB::table('products_attributes')
                            ->where('product_id', $productId)
                            ->where('attribute_id', $value)
                            ->exists();
                        if (!$exists) {
                            $fail('The selected attribute is not associated with the product.');
                        }
                    }
                },
            ],
            'definitions.*.value' => ['nullable', 'string'],
            'images' => ['sometimes', 'nullable', 'array'],
            'images.*' => ['required', new ImageOrBase64Rule()],
        ];
    }
}
