<?php
// =============================================================
//  api/v1/_response.php
//
//  Consistent JSON envelope for every api/v1/* endpoint. Mirrors the
//  {success, error, message} shape AuthMiddleware::jsonError() already
//  uses for the web app's own AJAX/API guards, so responses from this
//  new API don't look foreign next to the rest of the codebase.
// =============================================================

final class Api
{
    /** Success envelope: {success: true, data: ..., meta?: {...}}. */
    public static function success($data = null, array $meta = [], int $httpCode = 200): never
    {
        http_response_code($httpCode);
        $body = ['success' => true, 'data' => $data];
        if ($meta) $body['meta'] = $meta;
        echo json_encode($body);
        exit();
    }

    /** Error envelope: {success: false, error: "ShortCode", message: "human readable"}. */
    public static function error(int $httpCode, string $error, string $message, array $extra = []): never
    {
        http_response_code($httpCode);
        echo json_encode(array_merge([
            'success' => false,
            'error'   => $error,
            'message' => $message,
        ], $extra));
        exit();
    }

    /** Reads and JSON-decodes the request body. Sends 400 and exits if it isn't valid JSON. */
    public static function body(): array
    {
        $raw = file_get_contents('php://input');
        if (trim($raw) === '') return [];
        $decoded = json_decode($raw, true);
        if (!is_array($decoded)) {
            self::error(400, 'InvalidBody', 'Request body must be valid JSON');
        }
        return $decoded;
    }
}
