using System;
using System.Collections.Generic;
using System.Linq;

namespace TeleBot.Models
{
    public class ShoppingCart
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public List<CartItem> Items { get; set; } = new();
        public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
        public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
        
        public void AddItem(Guid productId, string productName, decimal price, int quantity = 1)
        {
            var existingItem = Items.FirstOrDefault(i => i.ProductId == productId);
            
            if (existingItem != null)
            {
                existingItem.Quantity += quantity;
                existingItem.UpdateTotalPrice();
            }
            else
            {
                var newItem = new CartItem
                {
                    ProductId = productId,
                    ProductName = productName,
                    UnitPrice = price,
                    Quantity = quantity
                };
                newItem.UpdateTotalPrice(); // Ensure total is calculated after all properties are set
                Items.Add(newItem);
            }
            
            UpdatedAt = DateTime.UtcNow;
        }
        
        public void RemoveItem(Guid productId)
        {
            Items.RemoveAll(i => i.ProductId == productId);
            UpdatedAt = DateTime.UtcNow;
        }
        
        public void UpdateQuantity(Guid productId, int quantity)
        {
            var item = Items.FirstOrDefault(i => i.ProductId == productId);
            if (item != null)
            {
                if (quantity <= 0)
                {
                    RemoveItem(productId);
                }
                else
                {
                    item.Quantity = quantity;
                    item.UpdateTotalPrice();
                    UpdatedAt = DateTime.UtcNow;
                }
            }
        }
        
        public void Clear()
        {
            Items.Clear();
            UpdatedAt = DateTime.UtcNow;
        }
        
        public decimal GetTotalAmount()
        {
            return Items.Sum(i => i.TotalPrice);
        }
        
        public int GetTotalItems()
        {
            return Items.Sum(i => i.Quantity);
        }
        
        public bool IsEmpty()
        {
            return !Items.Any();
        }
    }
    
    public class CartItem
    {
        public Guid ProductId { get; set; }
        public string ProductName { get; set; } = string.Empty;
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalPrice { get; set; }
        
        public CartItem()
        {
            // Don't calculate total in constructor - wait for properties to be set
        }
        
        public void UpdateTotalPrice()
        {
            TotalPrice = UnitPrice * Quantity;
        }
    }
}