<?php

declare(strict_types=1);

namespace App\Http\Requests;

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

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

    public function rules(): array
    {
        return [
            'member_id' => ['required', 'integer', Rule::exists('members', 'id')->whereNull('deleted_at')],
            'role_in_group' => ['nullable', Rule::enum(GroupMemberRole::class)],
        ];
    }

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

            if ($group->branch_id === null) {
                return;
            }

            $member = Member::query()->find($this->input('member_id'));

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