<?php

namespace App\Http\Requests\Api\V1\Member;

use App\Enums\RelationEnum;
use App\Http\Requests\Api\ApiFormRequest;
use App\Models\Dependent;
use App\Models\Member;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rule;

class StoreDependentRequest extends ApiFormRequest
{
    public function rules(): array
    {
        $member = $this->user();

        return [
            'name'     => ['required', 'string', 'max:255'],
            'relation' => ['required', 'integer', Rule::in(RelationEnum::values())],
            'dob'      => ['nullable', 'date', 'before:today'],
            'phone'    => [
                'nullable',
                'string',
                'regex:/^\+?[0-9]{10,20}$/',
                Rule::unique('dependents', 'phone')->where('assigned_member_id', $member->id),
            ],
        ];
    }

    public function messages(): array
    {
        return [
            'relation.in'  => __('Invalid relation type.'),
            'phone.unique' => __('This phone number is already used by another dependent.'),
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $member = $this->user();
            if (! $member instanceof Member) {
                $validator->errors()->add('member', __('Invalid member.'));

                return;
            }
            if (! $member->isFullAccess()) {
                $validator->errors()->add('member', __('Only Full Access members can add dependents.'));

                return;
            }
            if (! $member->hasActiveSubscription()) {
                $validator->errors()->add('subscription', __('Subscription must be active to add dependents.'));
            }
        });
    }

    protected function failedValidation(Validator $validator): void
    {
        throw new HttpResponseException(
            response()->json([
                'message' => __('Validation failed'),
                'status'  => false,
                'errors'  => $validator->errors(),
            ], 422)
        );
    }
}
