<?php

namespace App\Controllers;

use App\Services\Support\TenantContext;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class BaseController extends Controller
{
    protected $helpers = ['url', 'form'];

    protected TenantContext $tenant;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->tenant = TenantContext::getInstance();
    }

    protected function currentUser()
    {
        return $this->tenant->getUser();
    }

    protected function jsonSuccess($data = null, array $meta = [], int $status = 200)
    {
        return $this->response->setStatusCode($status)->setJSON([
            'success' => true,
            'data'    => $data,
            'meta'    => (object) $meta,
            'errors'  => [],
        ]);
    }

    protected function jsonError(array $errors, int $status = 400)
    {
        return $this->response->setStatusCode($status)->setJSON([
            'success' => false,
            'data'    => null,
            'errors'  => $errors,
        ]);
    }

    protected function jsonValidationError(array $fieldErrors)
    {
        $errors = [];
        foreach ($fieldErrors as $field => $message) {
            $errors[] = ['field' => $field, 'code' => 'VALIDATION_ERROR', 'message' => $message];
        }
        return $this->jsonError($errors, 422);
    }
}
