<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;

class ApiAuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        helper('security');

        $authorization = $request->getHeaderLine('Authorization');
        if (!$authorization || stripos($authorization, 'Bearer ') !== 0) {
            return $this->unauthorized('Missing or invalid Authorization header');
        }

        $token = trim(substr($authorization, 7));
        if ($token === '') {
            return $this->unauthorized('Bearer token is required');
        }

        try {
            $secret = require_env('JWT_SECRET');
        } catch (\RuntimeException $e) {
            return $this->unauthorized('JWT configuration is missing');
        }

        $payload = jwt_decode($token, $secret);

        if (!$payload || empty($payload['sub'])) {
            return $this->unauthorized('Invalid or malformed token');
        }

        if (isset($payload['exp']) && (int) $payload['exp'] < time()) {
            return $this->unauthorized('Token has expired');
        }

        $session = Services::session();
        $session->start();

        $session->set([
            'user_id' => (int) $payload['sub'],
            'roles'   => (array) ($payload['roles'] ?? []),
        ]);

        return null;
    }

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

    private function unauthorized(string $message)
    {
        $response = Services::response();
        return $response->setStatusCode(401)->setJSON([
            'status' => false,
            'message' => $message,
        ]);
    }
}
