using System.Collections.Generic;

using System.Data.SQLite;

using System.Threading.Tasks;

using Электронная_Фармация.Properties;



namespace Электронная_Фармация.Classes

{

    /// <summary>

    /// Synchronizes electronic invoices and refusals from API into local SQLite.

    /// </summary>

    public sealed class InvoiceSyncService

    {

        public async Task<int> SyncFromServerAsync()

        {

            var token = Settings.Default.stringToken;

            if (string.IsNullOrWhiteSpace(token))

            {

                throw new System.InvalidOperationException("Необходима авторизация перед загрузкой накладных.");

            }



            var client = new ApiClient();

            client.SetToken(token);

            var items = await client.GetInvoicesAsync();

            return SaveInvoices(items);

        }



        private static int SaveInvoices(IReadOnlyList<InvoiceApiItem> items)

        {

            if (items.Count == 0)

            {

                return 0;

            }



            using (var con = new SQLiteConnection(AppConfig.SqliteConnectionString))

            {

                con.Open();

                using (var tx = con.BeginTransaction())

                {

                    foreach (var item in items)

                    {

                        using (var cmd = new SQLiteCommand(@"

INSERT OR REPLACE INTO Invoice (InvoiceNumber, invoiceDate, SupplierName, ConsigneesName, InvoiceSum, RefuseSum)

VALUES (@number, @date, @supplier, @consignee, @sum, @refuseSum)", con, tx))

                        {

                            cmd.Parameters.AddWithValue("@number", item.InvoiceNumber ?? string.Empty);

                            cmd.Parameters.AddWithValue("@date", item.InvoiceDate ?? string.Empty);

                            cmd.Parameters.AddWithValue("@supplier", item.SupplierName ?? string.Empty);

                            cmd.Parameters.AddWithValue("@consignee", item.ConsigneeName ?? string.Empty);

                            cmd.Parameters.AddWithValue("@sum", item.InvoiceSum ?? string.Empty);

                            cmd.Parameters.AddWithValue("@refuseSum", item.RefuseSum ?? string.Empty);

                            cmd.ExecuteNonQuery();

                        }

                    }



                    tx.Commit();

                }

            }



            return items.Count;

        }

    }

}

