using OnlineSalesAutoCrop.CoreAPI.Models.Global;
using System;
using System.Collections.Generic;
using System.Linq;

namespace OnlineSalesAutoCrop.CoreAPI.Models.Objects.Setups
{
	public class BaseObject
	{
		public string Code { get; set; }
		public string Name { get; set; }
		public EnumStatus Status { get; set; }
		public short SeqId { get; set; }

		public string StatusDetail => Status.GetDescription();
		public string LastStatus => Status.GetLastDescription();
	}

	public class LookupData
	{
		public int ItemId { get; set; }
		public string ItemValue { get; set; }
	}

	public class LookupDataExt : LookupData
	{
		public int LookupId { get; set; }
		public short ItemType { get; set; }
		public string ItemCode { get; set; }
		public int SeqId { get; set; }
	}

	public class ProdByInvType
	{
		public int ProductId { get; set; }
		public string ProductCode { get; set; }
		public string ProductName { get; set; }
		public int InventoryTypeId { get; set; }
		public string InventoryType { get; set; }
		public string AstOrGLCode { get; set; }
		public string ExpOrDepGLCode { get; set; }
		public decimal Price { get; set; }
		public decimal VatRate { get; set; }
		public decimal AitRate { get; set; }
	}
	public class ProdByInvTypeExt : ProdByInvType
	{
		public int StoreId { get; set; }
		public decimal Stock { get; set; }
	}

	public class SalesTxnType
	{
		public int TranTypeId { get; set; }
		public string Description { get; set; }
		public string Side { get; set; }
	}

	public class HierarchyBase
	{
		public int HierarchyId { get; set; }
		public string Code { get; set; }
		public string Name { get; set; }
		public int LevelId { get; set; }
		public EnumStatus Status { get; set; }
		public int SeqId { get; set; }
		public int? ParentId { get; set; }

		public string StatusDetail => Status.GetDescription();
		public string LastStatus => Status.GetLastDescription();

		public List<HierarchyBase> Children { get; set; } = [];
		public bool HasChildren => Children != null && Children.Count > 0;

		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="parent"></param>
		/// <param name="data"></param>
		/// <exception cref="InvalidOperationException"></exception>
		public static void BuildHierarchy<T>(T parent, IEnumerable<T> data)
			where T : HierarchyBase
		{
			try
			{
				IEnumerable<T> children = data.Where(x => x.ParentId.HasValue && x.ParentId.Value == parent.HierarchyId);
				parent.Children.AddRange(children);
				foreach (T child in parent.Children.Cast<T>())
				{
					BuildHierarchy(parent: child, data: data);
				}
			}
			catch (Exception e)
			{
				throw new InvalidOperationException(e.Message, e);
			}
		}
	}
}