<?php

namespace App\Support;

use App\Lottery\ErrorCode;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 对外 API 统一 JSON 结构：{ code, msg, data }。
 *
 * - `code=0` 即 {@see ErrorCode::Success}；非 0 见 `ErrorCode` 与 docs/04 §10。
 * - error() 的 HTTP 状态可与 code 独立（如鉴权失败 401 + code 8001）。
 */
final class ApiResponse
{
    private const JSON_FLAGS = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;

    public static function success(mixed $data = null, ?string $msg = null, int $code = 0, ?Request $request = null): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg ?? ApiMessage::successMessage($request),
            'data' => $data,
        ], 200, [], self::JSON_FLAGS);
    }

    public static function error(string $msg, int $code, mixed $data = null, int $httpStatus = 400): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ], $httpStatus, [], self::JSON_FLAGS);
    }
}
