<?php

namespace App\Services;

use App\Models\Profile;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class PinService
{
      public function userHasPin(Profile $profile): bool
      {
            return !empty($profile->transaction_pin);
      }

      public function setPin(Profile $profile, string $pin): void
      {
            if (!preg_match('/^\d{4}$/', $pin)) {
                  throw ValidationException::withMessages([
                        'pin' => 'PIN must be exactly 4 digits.',
                  ]);
            }

            $profile->update([
                  'transaction_pin' => Hash::make($pin),
            ]);
      }

      public function verifyPin(Profile $profile, string $pin): void
      {
            if (!$this->userHasPin($profile)) {
                  throw ValidationException::withMessages([
                        'pin' => 'No transaction PIN set.',
                  ]);
            }

            if (!Hash::check($pin, $profile->transaction_pin)) {
                  throw ValidationException::withMessages([
                        'pin' => 'Incorrect transaction PIN.',
                  ]);
            }
      }
}
