<?php

namespace App\Filters;

use App\Services\Auth\PermissionService;
use App\Services\Support\TenantContext;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Route-level permission check. Configured per-route in Filters.php as:
 *   'roleguard:jobs.create'
 * The argument after the colon is the permission slug required.
 *
 * This is layer 1 of defense-in-depth (see 09-security-plan.md §2) — the
 * Service layer re-checks the same permission independently, so this filter
 * being misconfigured on one route can't be the only thing standing between
 * a user and an unauthorized write.
 */
class RoleGuard implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $user = TenantContext::getInstance()->getUser();

        if ($user === null) {
            // AuthFilter should have already blocked this, but fail closed.
            return $this->forbidden('Not authenticated.');
        }

        if (empty($arguments)) {
            return; // route only requires authentication, no specific permission
        }

        $requiredPermission = $arguments[0];
        $permissionService = new PermissionService();

        if (! $permissionService->can($user, $requiredPermission)) {
            return $this->forbidden("Missing required permission: {$requiredPermission}");
        }
    }

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

    private function forbidden(string $message)
    {
        return service('response')
            ->setStatusCode(403)
            ->setJSON(['success' => false, 'data' => null, 'errors' => [['code' => 'FORBIDDEN', 'message' => $message]]]);
    }
}
