<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class TransactionPinController extends Controller
{
    public function create(Request $request): JsonResponse
    {
        $request->validate([
            'pin' => ['required', 'string', 'digits:4', 'confirmed'],
        ]);

        $user = $request->user();

        if ($user->transaction_pin) {
            return response()->json(['message' => 'Transaction PIN already set.'], 400);
        }

        $user->transaction_pin = Hash::make($request->pin);
        $user->save();

        return response()->json(['message' => 'Transaction PIN created.']);
    }

    public function verify(Request $request): JsonResponse
    {
        $request->validate([
            'pin' => ['required', 'string', 'digits:4'],
        ]);

        $user = $request->user();

        if (! $user->transaction_pin || ! Hash::check($request->pin, $user->transaction_pin)) {
            return response()->json(['message' => 'Incorrect PIN.'], 422);
        }

        return response()->json(['message' => 'PIN verified.']);
    }
}