<?php

namespace App\Filters;

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

/**
 * AuthFilter already populates TenantContext for every authenticated
 * request. This filter is the explicit "this route MUST have a resolved
 * agency" guard — used on agency-only routes (jobs, ATS, billing, etc.)
 * to reject candidates/super-admins hitting them with a clear error
 * instead of silently returning empty (WHERE 1=0) result sets from
 * BaseRepository.
 *
 * Order in route filter chains: ['auth', 'tenant', 'roleguard:...']
 */
class TenantScope implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $tenant = TenantContext::getInstance();

        if ($tenant->isSuperAdmin()) {
            return; // super admin routes handle their own explicit scoping
        }

        if ($tenant->getAgencyId() === null) {
            return service('response')
                ->setStatusCode(403)
                ->setJSON([
                    'success' => false,
                    'data'    => null,
                    'errors'  => [['code' => 'NO_TENANT_CONTEXT', 'message' => 'This action requires an agency account.']],
                ]);
        }
    }

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