<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'sku' => ['nullable', 'string', 'max:64', 'unique:inventory_products,sku'],
            'name' => ['required', 'string', 'max:255'],
            'product_type_id' => ['required', 'integer', 'exists:inventory_product_types,id'],
            'brand_id' => ['nullable', 'integer', 'exists:inventory_brands,id'],
            'category_id' => ['nullable', 'integer', 'exists:inventory_categories,id'],
            'subcategory_id' => ['nullable', 'integer', 'exists:inventory_subcategories,id'],
            'supplier_id' => ['nullable', 'integer', 'exists:inventory_suppliers,id'],
            'min_stock' => ['nullable', 'numeric', 'min:0'],
            'active' => ['sometimes', 'boolean'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator): void {
            $cat = $this->input('category_id');
            $sub = $this->input('subcategory_id');
            if ($sub && $cat) {
                $exists = \App\Models\InventorySubcategory::query()
                    ->whereKey($sub)
                    ->where('category_id', $cat)
                    ->exists();
                if (! $exists) {
                    $validator->errors()->add('subcategory_id', 'La subcategoría no pertenece a la categoría seleccionada.');
                }
            }
        });
    }
}
