<?php

namespace App\Filters;

use App\Libraries\ChurchContext;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class ChurchScopeFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null): mixed
    {
        $ctx = ChurchContext::getInstance();

        // Platform admins do not have a church_id; let controllers handle scoping.
        if ($ctx->isPlatformAdmin()) {
            return null;
        }

        $churchId = $ctx->getChurchId();

        if (!$churchId) {
            return response()
                ->setStatusCode(401)
                ->setContentType('application/json')
                ->setJSON(['status' => 'error', 'message' => 'Unable to determine church context']);
        }

        return null;
    }

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