using System.Diagnostics.CodeAnalysis;
using System.Net;

namespace Pilz.Net.Api;

public record class ApiResponse<T>(
    HttpResponseMessage? Response,
    T? Message)
    where T : ApiMessage
{
    public HttpStatusCode StatusCode => Response?.StatusCode ?? default;

    [MemberNotNullWhen(true, nameof(Message))]
    public bool IsOk => (int)StatusCode >= 200 && (int)StatusCode <= 299 && Message is not null;

    [MemberNotNull(nameof(Message))]
    public T EnsureOk()
    {
        if (!IsOk)
            throw new ApiException("Api return is not ok or message invalid: " + StatusCode, StatusCode);
        return Message;
    }
}
