using System.Net;
using IdokladSdk.Response;

namespace Idoklad.Client;

/// <summary>
/// Helpers that unwrap the SDK's <see cref="ApiResult{TData}"/> envelope, returning the payload
/// on success and translating failures into <see cref="IdokladApiException"/>.
/// </summary>
public static class ApiResultExtensions
{
    public static TData Unwrap<TData>(this ApiResult<TData> result)
    {
        if (result is null)
        {
            throw new IdokladApiException(HttpStatusCode.BadGateway, default, "Empty response from iDoklad API.");
        }

        if (!result.IsSuccess)
        {
            var status = result.StatusCode == 0 ? HttpStatusCode.BadGateway : result.StatusCode;
            throw new IdokladApiException(status, result.ErrorCode, result.Message);
        }

        return result.Data;
    }
}
