<?php

namespace App\Controllers\Api;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

abstract class BaseApiController extends BaseController
{
    use ResponseTrait;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->response->setHeader('Content-Type', 'application/json');
    }

    /**
     * Standard success JSON: { "data": ..., "error": null }
     */
    protected function success($data = null, int $status = 200): \CodeIgniter\HTTP\ResponseInterface
    {
        return $this->respond([
            'data'  => $data,
            'error' => null,
        ], $status);
    }

    /**
     * Standard error JSON: { "data": null, "error": { "code": ..., "message": ... } }
     */
    protected function error(string $message, int $status = 400, ?string $code = null): \CodeIgniter\HTTP\ResponseInterface
    {
        return $this->respond([
            'data'  => null,
            'error' => [
                'code'    => $code ?? (string) $status,
                'message' => $message,
            ],
        ], $status);
    }
}
