<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class AssignPlantsRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        $rows = $this->input('rows');
        if (is_string($rows)) {
            $rows = array_filter(array_map('trim', explode(',', $rows)));
        }

        $createVariation = $this->input('create_variation');
        if (is_string($createVariation)) {
            $decoded = json_decode($createVariation, true);
            $createVariation = is_array($decoded) ? $decoded : null;
        }

        $this->merge([
            'rows' => $rows,
            'create_variation' => $createVariation,
        ]);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'rows' => ['required', 'array', 'min:1'],
            'rows.*' => ['integer', 'exists:vineyard_rows,id'],
            'variety_variation_id' => ['nullable', 'integer', 'exists:variety_variations,id', 'required_without:create_variation'],
            'create_variation' => ['nullable', 'array', 'required_without:variety_variation_id'],
            'create_variation.grape_variety_id' => ['nullable', 'integer', 'exists:grape_varieties,id'],
            'create_variation.grape_variety_name' => ['nullable', 'string', 'max:255'],
            'create_variation.color' => ['required_without:variety_variation_id', 'string', 'max:50'],
            'create_variation.description' => ['nullable', 'string'],
            'create_variation.typical_sugar_content' => ['nullable', 'numeric', 'min:0'],
            'create_variation.typical_alcohol' => ['nullable', 'numeric', 'min:0'],
            'create_variation.ripening_period' => ['nullable', 'string', 'max:255'],
        ];
    }
}
