<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use App\Libraries\JwtService;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $header = $request->getHeaderLine("Authorization");

        if (!$header || !str_contains($header, 'Bearer ')) {
            return service('response')->setJSON([
                'status' => false,
                'message' => 'Unauthorized'
            ])->setStatusCode(401);
        }

        try {
            $token = str_replace('Bearer ', '', $header);

            $jwt = new JwtService();
            $decoded = $jwt->decode($token);

            // inject user ke request
            $request->user = $decoded->data;

        } catch (\Exception $e) {
            return service('response')->setJSON([
                'status' => false,
                'message' => 'Token tidak valid / expired'
            ])->setStatusCode(401);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}