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

namespace Pilz.Net.Api.Client;

public abstract class BaseChildItemClient<T>(IApiClient client) : BaseClient<T>(client), IBaseChildItemClient<T> where T : IDataObject
{
    public override string ApiEndpoint => ApiEndpointParent + ApiEndpointChild;
    public abstract string ApiEndpointParent { get; }
    public abstract string ApiEndpointChild { get; }

    public virtual async Task<IEnumerable<T>> GetAll(int parentId) 
    {
        return (await client.SendRequest<GeneralItemMessages<T>.Items>($"{ApiEndpointParent}/{parentId}{ApiEndpointChild}", HttpMethod.Get)).EnsureOk().Items;
    }

    public virtual async Task<IEnumerable<T>> GetAll(int parentId, int offset, int count)
    {
        return (await client.SendRequest<GeneralItemMessages<T>.Items>(ApiEndpoint, HttpMethod.Get, new ApiParameterCollection
        {
            ["offset"] = offset,
            ["count"] = count,
        })).EnsureOk().Items;
    }

    public override async Task<T> Save(T item)
    {
        if (item.Id == 0)
            throw new NullReferenceException("Item has no parent yet!");
        return await base.Save(item);
    }

    public virtual async Task<T> Save(T item, int parentId)
    {
        if (item.Id != 0)
            return await Save(item);
        return (await client.SendRequest<GeneralItemMessages<T>.Item>(
            $"{ApiEndpointParent}/{parentId}{ApiEndpointChild}",
            HttpMethod.Post,
            GenerateUpdateMessage(item, true))).EnsureOk().Item;
    }
}
