<?php

namespace App\Modules\Integrations\Platform\Support;

use Illuminate\Http\JsonResponse;

final class ApiResponseFactory
{
    /**
     * @param  array<string, mixed>|list<mixed>|null  $data
     * @param  array<string, mixed>  $meta
     */
    public function ok(array $data = null, array $meta = [], int $status = 200): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => $data,
            'error' => null,
            'meta' => $meta + $this->defaultMeta(),
        ], $status);
    }

    public function accepted(array $data = null, array $meta = []): JsonResponse
    {
        return $this->ok($data, $meta, 202);
    }

    public function error(ApiErrorResponse $error, int $status, array $meta = []): JsonResponse
    {
        return response()->json([
            'success' => false,
            'data' => null,
            'error' => $error->toArray(),
            'meta' => $meta + $this->defaultMeta(),
        ], $status);
    }

    /**
     * @return array{request_id: string|null}
     */
    private function defaultMeta(): array
    {
        /** @var string|null $rid */
        $rid = request()->attributes->get('request_id');

        return ['request_id' => $rid];
    }
}

