using System;
using System.Threading.Tasks;

namespace WK5.Core.OpenCart.Karley
{
    public class KarleyProductDiscount : ProductDiscount
    {
        public bool Updated { get; set; } = false;

        public static async Task<KarleyProductDiscount?> GetDiscountAsync(int product_discount_id)
        {
            return await GetDiscountAsync<KarleyProductDiscount>(new KarleyProductDiscount(), product_discount_id, GlobalConfig.KarleyMySql);
        }

        public static async Task<KarleyProductDiscount> CreateDiscountAsync(KarleyProductDiscount discount)
        {
            string sql = @"INSERT INTO `product_discount` (product_id, customer_group_id, quantity, priority, price, date_start, date_end, updated)
VALUES 
(@product_id, @customer_group_id, @quantity, @priority, @price, @date_start, @date_end, @updated)";

            using MySqlController2 mySqlController = new MySqlController2(GlobalConfig.KarleyMySql);

            mySqlController.AddParameter("@product_id", discount.ProductId);
            mySqlController.AddParameter("@customer_group_id", discount.CustomerGroupId);
            mySqlController.AddParameter("@quantity", discount.Quantity);
            mySqlController.AddParameter("@priority", discount.Priority);
            mySqlController.AddParameter("@price", discount.Price);
            mySqlController.AddParameter("@date_start", discount.DateStart is null ? "0000-00-00" : discount.DateStart);
            mySqlController.AddParameter("@date_end", discount.DateEnd is null ? "0000-00-00" : discount.DateEnd);
            mySqlController.AddParameter("@updated", discount.Updated);

            await mySqlController.QueryAsync(sql);

            var idObj = await mySqlController.FetchObjectAsync("SELECT LAST_INSERT_ID()");

            if (idObj is not null)
            {
                discount.ProductDiscountId = Convert.ToInt32(idObj);
            }

            return discount;
        }

        public static async Task DeleteDiscountsAsync(int product_id)
        {
            await DeleteDiscountsAsync(product_id, GlobalConfig.KarleyMySql);
        }
    }
}
