<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JWTAuth implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $authHeader = $request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return service('response')
                ->setStatusCode(401)
                ->setJSON(['error' => 'Missing or invalid token']);
        }

        $token = substr($authHeader, 7); // Remove "Bearer " prefix
        $secretKey = getenv('JWT_SECRET') ?: 'secret12345678';

        try {
            $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));

            // Optionally pass user data to request for controller access
            $request->user = $decoded;

        } catch (\Exception $e) {
            return service('response')
                ->setStatusCode(401)
                ->setJSON(['error' => 'Token invalid: ' . $e->getMessage()]);
        }

        return null; // Allow request to proceed
    }

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