<?php

namespace App\Filters;

use App\Modules\Auth\Entities\Role;
use App\Modules\Auth\Services\AuthService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Admin Only Filter
 *
 * Allows access only if user is logged in and has role ADMIN. Otherwise 401 or 403.
 */
class AdminOnlyFilter implements \CodeIgniter\Filters\FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $authService = new AuthService();
        $user       = $authService->currentUser();

        if ($user === null) {
            return service('response')
                ->setStatusCode(401)
                ->setJSON([
                    'success' => false,
                    'message' => 'Unauthorized',
                    'data'    => null,
                ]);
        }

        $roles   = $user['roles'] ?? [];
        $codes   = array_column($roles, 'role_code');
        if (!in_array(Role::CODE_ADMIN, $codes, true)) {
            return service('response')
                ->setStatusCode(403)
                ->setJSON([
                    'success' => false,
                    'message' => 'Forbidden: Admin only',
                    'data'    => null,
                ]);
        }

        return null;
    }

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