<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Enums\GroupType;
use App\Models\Member;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class UpdateGroupRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('update', $this->route('group'));
    }

    public function rules(): array
    {
        return [
            'name' => ['sometimes', 'string', 'max:150'],
            'type' => ['sometimes', Rule::enum(GroupType::class)],
            'description' => ['nullable', 'string'],
            'leader_member_id' => ['nullable', 'integer', Rule::exists('members', 'id')->whereNull('deleted_at')],
            'is_active' => ['sometimes', 'boolean'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $group = $this->route('group');

            if ($group->branch_id === null || ! $this->filled('leader_member_id')) {
                return;
            }

            $leader = Member::query()->find($this->input('leader_member_id'));

            if ($leader && (int) $leader->branch_id !== (int) $group->branch_id) {
                $validator->errors()->add('leader_member_id', 'The leader must belong to the same branch as the group.');
            }
        });
    }
}
