<?php

namespace App\Http\Requests;

use App\Models\Project;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

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

    public function rules(): array
    {
        return [
            'title' => 'sometimes|required|string|max:255',
            'description' => 'nullable|string',
            'project_id' => 'sometimes|required|exists:projects,id',
            'assignee_id' => 'nullable|exists:users,id',
            'priority' => 'nullable|string|max:50',
            'status' => 'nullable|string|max:50',
            'blocker_type' => 'nullable|string|max:80',
            'blocker_note' => 'nullable|string',
            'start_date' => 'nullable|date',
            'due_date' => 'nullable|date',
            'estimated_time' => 'nullable|numeric',
            'actual_time' => 'nullable|numeric',
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            if (! $this->filled('assignee_id')) {
                return;
            }

            $task = $this->route('task');
            $projectId = $this->input('project_id', $task?->project_id);
            $project = Project::with('members:id')->find($projectId);
            if (! $project) {
                return;
            }

            $assigneeId = (int) $this->input('assignee_id');
            $isApprovedProjectMember = $assigneeId === (int) $project->project_manager_id
                || $project->members->contains('id', $assigneeId);

            if (! $isApprovedProjectMember) {
                $validator->errors()->add('assignee_id', 'مسئول جدید باید از اعضای تأییدشده همین پروژه باشد.');
            }
        });
    }
}
