<?php

namespace App\Controllers\Api;

use App\Libraries\ChurchContext;
use App\Libraries\PermissionService;
use App\Libraries\ResponseHelper;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\ResponseInterface;

abstract class BaseApiController extends Controller
{
    protected ChurchContext $ctx;

    public function initController(
        \CodeIgniter\HTTP\RequestInterface $request,
        \CodeIgniter\HTTP\ResponseInterface $response,
        \Psr\Log\LoggerInterface $logger
    ): void {
        parent::initController($request, $response, $logger);
        $this->ctx = ChurchContext::getInstance();
    }

    protected function requirePermission(string $permission): ?ResponseInterface
    {
        if (!PermissionService::has($permission)) {
            return ResponseHelper::forbidden('You do not have permission to perform this action');
        }
        return null;
    }

    protected function churchId(): int
    {
        return (int) $this->ctx->getChurchId();
    }

    protected function currentUser(): array
    {
        return $this->ctx->getUser() ?? [];
    }

    protected function scopedModel(\App\Models\BaseModel $model): \App\Models\BaseModel
    {
        return $model->setChurchId($this->churchId());
    }

    protected function getJson(): array
    {
        return $this->request->getJSON(true) ?? [];
    }

    protected function getPerPage(int $default = 20): int
    {
        $pp = (int) ($this->request->getGet('per_page') ?? $default);
        return min(max($pp, 5), 100);
    }
}
