<?php

namespace App\Support;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;

final class ApiResponse
{
    public const API_VERSION = '2026-07-01';

    public static function success(mixed $data = null, int $status = 200, array $meta = []): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => $data,
            'meta' => array_merge(self::baseMeta(), $meta),
        ], $status);
    }

    public static function error(string $code, string $message, int $status, array $details = [], array $meta = []): JsonResponse
    {
        return response()->json([
            'success' => false,
            'error' => ['code' => $code, 'message' => $message, 'details' => (object) $details],
            'meta' => array_merge(self::baseMeta(false), $meta),
        ], $status);
    }

    private static function baseMeta(bool $includeVersion = true): array
    {
        $request = request();
        $requestId = $request->attributes->get('request_id') ?? 'req_'.Str::ulid();
        $meta = ['request_id' => $requestId];
        if ($includeVersion) $meta['api_version'] = self::API_VERSION;
        return $meta;
    }
}
