<?php

namespace App\Filters;

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

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

        $authHeader = $request->getHeaderLine('Authorization');

        if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
            $token = trim(substr($authHeader, 7));

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

                if (!isset($decoded->roles) || empty($decoded->roles->admin)) {
                    return $this->denyAccess('Admin privileges required.', ResponseInterface::HTTP_FORBIDDEN);
                }
            } catch (\Throwable $e) {
                return $this->denyAccess('Invalid or expired token.', ResponseInterface::HTTP_UNAUTHORIZED);
            }
        } else {
            $session = session();
            if (!$session->get('isLoggedIn') || $session->get('role') !== 'admin') {
                if (strpos($request->getHeaderLine('Accept'), 'text/html') !== false) {
                    return redirect()->to(base_url('login'))->with('error', 'Please log in to access API documentation.');
                }
                return $this->denyAccess('Unauthorized access to documentation.', ResponseInterface::HTTP_UNAUTHORIZED);
            }
        }
    }

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

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