<?php

namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class Auth implements FilterInterface
{
    private const TOKEN_PREFIX = 'admin_token_';

    public function before(RequestInterface $request, $arguments = null)
    {
        $authHeader = $request->getHeaderLine('Authorization');
        if (preg_match('/Bearer\s+(\S+)/', $authHeader, $m)) {
            $token = $m[1];
            $cache = \Config\Services::cache();
            $payload = $cache->get(self::TOKEN_PREFIX . $token);
            if (is_array($payload) && !empty($payload['username'])) {
                session()->set('isLoggedIn', true);
                session()->set('admin_username', $payload['username']);
                return;
            }
            // Token present but invalid - return 401 JSON for API clients
            return \Config\Services::response()
                ->setJSON(['error' => 'Unauthorized'])
                ->setStatusCode(401);
        }

        if (!session()->get('isLoggedIn')) {
            $accept = $request->getHeaderLine('Accept');
            if (strpos($accept, 'application/json') !== false) {
                return \Config\Services::response()
                    ->setJSON(['error' => 'Unauthorized'])
                    ->setStatusCode(401);
            }
            return redirect()->to('/admin/login');
        }
    }

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