<?php

namespace App\Filters;

use App\Services\ApiTokenService;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class ApiTokenFilter implements FilterInterface
{
    public function before(RequestInterface $request,$arguments=null)
    {
        $header=(string)$request->getHeaderLine('Authorization');
        if(!preg_match('/^Bearer\s+(.+)$/i',$header,$m))return service('response')->setStatusCode(401)->setJSON(['error'=>'Bearer token required']);
        $user=(new ApiTokenService())->authenticate(trim($m[1]));
        if(!$user)return service('response')->setStatusCode(401)->setJSON(['error'=>'Invalid or expired token']);
        $GLOBALS['tibaleta_api_user']=$user;
    }
    public function after(RequestInterface $request,ResponseInterface $response,$arguments=null){ unset($GLOBALS['tibaleta_api_user']); }
}
