<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $task = $this->route('task');
        $taskableType = $task->taskable_type;

        // For spraying and harvest tasks, date cannot be changed
        $dateRules = (str_contains($taskableType, 'Spraying') || str_contains($taskableType, 'Harvest'))
            ? ['nullable', 'date']
            : ['required', 'date', 'after_or_equal:today'];

        $rules = [
            'planned_date' => $dateRules,
            'note' => ['nullable', 'string', 'max:1000'],
            'task_ids' => ['nullable', 'array', 'min:1'],
            'task_ids.*' => ['integer', 'exists:planned_tasks,planned_task_id'],
        ];

        // Add type-specific validation rules based on taskable type
        if (str_contains($taskableType, 'Watering')) {
            $rules['time_interval'] = ['nullable', 'integer', 'min:1'];
            $rules['amount'] = ['required', 'numeric', 'min:0.01'];
        } elseif (str_contains($taskableType, 'Fertilization')) {
            $rules['substance'] = ['required', 'string', 'max:255'];
            $rules['concentration'] = ['nullable', 'numeric', 'min:0'];
        } elseif (str_contains($taskableType, 'Spraying')) {
            $rules['pesticide'] = ['required', 'string', 'max:255'];
            $rules['concentration'] = ['nullable', 'numeric', 'min:0'];
        } elseif (str_contains($taskableType, 'Pruning')) {
            $rules['method'] = ['required', 'string', 'max:255'];
            $rules['percentage_removed'] = ['nullable', 'integer', 'min:0', 'max:100'];
        }
        // Harvest doesn't have editable details fields (they're filled when completed)

        return $rules;
    }
}
