<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Models\Member;
use App\Models\MemberTransfer;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class StoreTransferRequest extends FormRequest
{
    public function authorize(): bool
    {
        $member = Member::visibleTo($this->user())->find($this->input('member_id'));

        if ($member === null) {
            return false;
        }

        return $this->user()->can('create', [MemberTransfer::class, $member->branch_id]);
    }

    public function rules(): array
    {
        return [
            'member_id' => ['required', 'integer', 'exists:members,id'],
            'to_branch_id' => ['required', 'integer', 'exists:branches,id'],
            'reason' => ['nullable', 'string', 'max:255'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $member = Member::visibleTo($this->user())->find($this->input('member_id'));

            if ($member && (int) $member->branch_id === (int) $this->input('to_branch_id')) {
                $validator->errors()->add('to_branch_id', 'The member is already in this branch.');
            }
        });
    }
}
