<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Models\Household;
use App\Services\MemberRules;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

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

    public function rules(): array
    {
        return MemberRules::forUpdate();
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            if (! $this->has('household_id') || $this->input('household_id') === null) {
                return;
            }

            $household = Household::query()->find($this->input('household_id'));
            $member = $this->route('member');

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