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

namespace Pilz.Net.Api.Client;

public abstract class BaseChildItemClient<T>(IApiClient client) : BaseClient<T>(client), IBaseChildItemClient<T> where T : IDataObject
{
    public virtual async Task<IEnumerable<T>> GetAll(int parentId) 
    {
        return (await client.SendRequest<GeneralItemMessages<T>.Items>(ApiEndpoint, HttpMethod.Get, new ApiParameterCollection
        {
            ["parent"] = parentId,
        })).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>(
            ApiEndpoint,
            HttpMethod.Post,
            GenerateUpdateMessage(item, true),
            new ApiParameterCollection
            {
                ["parent"] = parentId,
            })).EnsureOk().Item;
    }
}
