<?php
namespace App\Traits;

use App\Services\PinService;
use Illuminate\Validation\ValidationException;

trait RequiresPin
{
    public bool $pinMissing = false;
    public string $pin = '';
    public bool $awaitingPin = false;
    protected $onPinCreatedCallback = null;

    protected function requirePin(PinService $pinService, callable $onSuccess): void
    {
        if (!$pinService->userHasPin(auth()->user()->profile)) {
            $this->pinMissing = true;
            $this->awaitingPin = true;
            $this->addError(
                'pin',
                'For your security, please create a 4-digit transaction PIN to continue.'
            );
            return;
        }

        // PIN exists → continue immediately
        $onSuccess();
    }

    public function createPin(PinService $pinService): void
    {

        try {
            $pinService->setPin(auth()->user()->profile, $this->pin);
        } catch (ValidationException $e) {
            $this->addError('pin', $e->getMessage());
            return;
        }

        $this->pinMissing = false;
        $this->awaitingPin = false;
        $this->resetPinState();
        $this->dispatch('pin-success');
        $this->dispatch('showToast', message: 'Pin Created Successfully!.', type: 'success');
        if ($this->onPinCreatedCallback) {
            ($this->onPinCreatedCallback)();
            $this->onPinCreatedCallback = null;
        }
    }
    /**
     * Verify PIN before final action
     */
    protected function verifyPin(PinService $pinService): bool
    {
        try {
            $pinService->verifyPin(auth()->user()->profile, $this->pin);
        } catch (ValidationException $e) {
            $this->addError('pin', $e->getMessage());
            return false;
        }

        return true;
    }
    protected function resetPinState(): void
    {
        $this->pin = '';
        $this->resetErrorBag('pin');
        $this->awaitingPin = false;
    }
}
