using Pilz.Data;
using Pilz.Net.Api.Messages;

namespace Pilz.Net.Api.Client;

public abstract class BaseClient<T>(IApiClient client) : IBaseClient<T> where T : IDataObject
{
    public abstract string ApiEndpoint { get; }

    public virtual async Task<T> Get(int id)
    {
        return (await client.SendRequest<GeneralItemMessages<T>.Item>($"{ApiEndpoint}/{id}", HttpMethod.Get)).EnsureOk().Item;
    }

    public virtual async Task Delete(int id)
    {
        (await client.SendRequest($"{ApiEndpoint}/{id}", HttpMethod.Delete)).EnsureOk();
    }

    public virtual async Task<T> Save(T item)
    {
        var generateNew = item.Id == 0;
        return (await client.SendRequest<GeneralItemMessages<T>.Item>(
            generateNew ? ApiEndpoint : $"{ApiEndpoint}/{item.Id}",
            generateNew ? HttpMethod.Post : HttpMethod.Put,
            GenerateUpdateMessage(item, generateNew))).EnsureOk().Item;
    }

    protected abstract ApiMessage GenerateUpdateMessage(T item, bool generateNew);
}
