using salesbook.Shared.Core.Helpers;
using salesbook.Shared.Core.Interface;
using salesbook.Shared.Core.Interface.IntegryApi;

namespace salesbook.Maui.Core.Services;

public class SyncDbService(IIntegryApiService integryApiService, LocalDbService localDb) : ISyncDbService
{
    public async Task GetAndSaveCommesse(string? dateFilter)
    {
        var allCommesse = await integryApiService.RetrieveAllCommesse(dateFilter);

        if (!allCommesse.IsNullOrEmpty())
            if (dateFilter is null)
                await localDb.InsertAll(allCommesse!);
            else
                await localDb.InsertOrUpdate(allCommesse!);
    }

    public async Task GetAndSaveSettings(string? dateFilter)
    {
        if (dateFilter is not null)
            await localDb.ResetSettingsDb();

        var settingsResponse = await integryApiService.RetrieveSettings();

        if (!settingsResponse.ActivityResults.IsNullOrEmpty())
            await localDb.InsertAll(settingsResponse.ActivityResults!);

        if (!settingsResponse.ActivityTypes.IsNullOrEmpty())
            await localDb.InsertAll(settingsResponse.ActivityTypes!);

        if (!settingsResponse.ActivityTypeUsers.IsNullOrEmpty())
            await localDb.InsertAll(settingsResponse.ActivityTypeUsers!);

        if (!settingsResponse.StbUsers.IsNullOrEmpty())
            await localDb.InsertAll(settingsResponse.StbUsers!);

        if (!settingsResponse.VtbTipi.IsNullOrEmpty())
            await localDb.InsertAll(settingsResponse.VtbTipi!);

        if (!settingsResponse.Nazioni.IsNullOrEmpty())
            await localDb.InsertAll(settingsResponse.Nazioni!);
    }
}