<?php

declare(strict_types=1);

namespace App\Http\Requests;

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

class StoreMemberRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', [Member::class, $this->input('branch_id')]);
    }

    public function rules(): array
    {
        return [
            ...MemberRules::forCreate(),
            'branch_id' => ['required', 'integer', 'exists:branches,id'],
        ];
    }

    protected function prepareForValidation(): void
    {
        // Schema doc: default `member` is for the import path only — manual
        // creates through the API default to `visitor` unless specified.
        if (! $this->filled('membership_status')) {
            $this->merge(['membership_status' => MembershipStatus::Visitor->value]);
        }
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $householdId = $this->input('household_id');

            if ($householdId === null) {
                return;
            }

            $household = Household::query()->find($householdId);

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