<?php

namespace App\Http\Requests;

use App\Models\PurchaseProduct;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class SyncFactoryProductRecipeRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user()?->can('factory-products.update');
    }

    protected function prepareForValidation(): void
    {
        $lines = collect($this->input('recipe_lines', []))
            ->map(function (mixed $line): array {
                if (! is_array($line)) {
                    return [
                        'purchase_product_id' => null,
                        'quantity' => null,
                    ];
                }

                return [
                    'purchase_product_id' => $line['purchase_product_id'] ?? null,
                    'quantity' => $line['quantity'] ?? null,
                ];
            })
            ->filter(function (array $line): bool {
                return filled($line['purchase_product_id']) && filled($line['quantity']);
            })
            ->values()
            ->all();

        $this->merge([
            'recipe_lines' => $lines,
        ]);
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'recipe_lines' => ['required', 'array', 'min:1'],
            'recipe_lines.*.purchase_product_id' => [
                'required',
                'integer',
                Rule::exists(PurchaseProduct::class, 'id')->where('is_active', true),
            ],
            'recipe_lines.*.quantity' => ['required', 'numeric', 'gt:0'],
        ];
    }
}
