<?php

namespace App\Core;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Base API Controller
 * 
 * Provides standardized JSON response methods for all API controllers.
 * All responses follow a consistent format:
 * {
 *   success: boolean,
 *   message: string,
 *   data: mixed,
 *   meta?: object
 * }
 */
abstract class BaseApiController extends BaseController
{
    /**
     * Send a successful JSON response
     * 
     * @param mixed $data Response data
     * @param string $message Success message
     * @param array|null $meta Optional metadata
     * @param int $statusCode HTTP status code (default: 200)
     * @return ResponseInterface
     */
    protected function successResponse(
        mixed $data = null,
        string $message = 'Success',
        ?array $meta = null,
        int $statusCode = ResponseInterface::HTTP_OK
    ): ResponseInterface {
        $response = [
            'success' => true,
            'message' => $message,
            'data' => $data,
        ];

        if ($meta !== null) {
            $response['meta'] = $meta;
        }

        return $this->response
            ->setStatusCode($statusCode)
            ->setJSON($response);
    }

    /**
     * Send an error JSON response
     * 
     * @param string $message Error message
     * @param mixed $data Optional error data
     * @param array|null $meta Optional metadata
     * @param int $statusCode HTTP status code (default: 400)
     * @return ResponseInterface
     */
    protected function errorResponse(
        string $message = 'An error occurred',
        mixed $data = null,
        ?array $meta = null,
        int $statusCode = ResponseInterface::HTTP_BAD_REQUEST
    ): ResponseInterface {
        $response = [
            'success' => false,
            'message' => $message,
            'data' => $data,
        ];

        if ($meta !== null) {
            $response['meta'] = $meta;
        }

        return $this->response
            ->setStatusCode($statusCode)
            ->setJSON($response);
    }
}
