<?php

namespace Modules\Tpin\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Tpin\Services\TpinService;

/**
 * Route filter for TPIN-protected actions.
 * Usage: ['filter' => 'tpin'] or combined with permission filters.
 *
 * Client flow: EnterpriseTpin.confirm() → POST /tpin/verify → submit/navigate.
 * This filter consumes the short-lived session flag set by verify().
 */
class TpinFilter implements FilterInterface
{
    public const SESSION_KEY = 'tpin_verified_at';
    public const VALID_SECONDS = 300;

    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();
        $userId  = (int) $session->get('user_id');

        if ($userId <= 0) {
            return redirect()->to(config('Auth')->loginUrl);
        }

        $result = (new TpinService())->assertConfirmedForAction($userId);
        if ($result['ok']) {
            return;
        }

        $session->setFlashdata('error', $result['error'] ?? 'TPIN confirmation is required for this action.');

        if (! empty($result['redirect'])) {
            return redirect()->to($result['redirect']);
        }

        $session->set('tpin_return_url', current_url());

        return redirect()->back();
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No-op.
    }
}
