<?php

namespace Modules\Auth\Filters;

use App\Models\RoleModel;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Auth\Services\AuthService;

class AdminFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        if (! $session->get('isLoggedIn')) {
            return redirect()->to(config('Auth')->loginUrl);
        }

        if (! $this->isAdministrator($session)) {
            $session->setFlashdata('error', 'Administrator access required.');

            $roleId = $session->get('role_id') ? (int) $session->get('role_id') : null;
            $redirect = (new AuthService())->permissionDeniedRedirectUrl(
                null,
                $roleId,
                $request->getUri()->getPath()
            );

            return redirect()->to($redirect);
        }
    }

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

    private function isAdministrator($session): bool
    {
        $roleSlug = $session->get('role_slug');

        if ($roleSlug === null) {
            $roleId = $session->get('role_id');
            if ($roleId) {
                $role = (new RoleModel())->find((int) $roleId);
                $roleSlug = $role['slug'] ?? null;
                $session->set('role_slug', $roleSlug);
            }
        }

        return $roleSlug === 'administrator';
    }
}
