<?php

namespace App\Http\Requests\Api\User;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;

class UpdateCardPinRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'current_pin' => [
                'required',
                'string',
                'size:4',
                'regex:/^\d{4}$/' // Only 4 digits
            ],
            'new_pin' => [
                'required',
                'string',
                'size:4',
                'regex:/^\d{4}$/', // Only 4 digits
                'different:current_pin'
            ],
            'confirm_pin' => [
                'required',
                'string',
                'same:new_pin'
            ]
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages(): array
    {
        return [
            'current_pin.required' => 'Current PIN is required.',
            'current_pin.size' => 'Current PIN must be exactly 4 digits.',
            'current_pin.regex' => 'Current PIN must contain only numbers.',
            'new_pin.required' => 'New PIN is required.',
            'new_pin.size' => 'New PIN must be exactly 4 digits.',
            'new_pin.regex' => 'New PIN must contain only numbers.',
            'new_pin.different' => 'New PIN must be different from current PIN.',
            'confirm_pin.required' => 'PIN confirmation is required.',
            'confirm_pin.same' => 'PIN confirmation must match new PIN.'
        ];
    }

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Http\Exceptions\HttpResponseException
     */
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(
            response()->json([
                'status' => 'error',
                'message' => $validator->errors()->first(),
                'errors' => $validator->errors()
            ], 422)
        );
    }
}
