using System;
using System.ComponentModel;
using System.Collections.Concurrent;
using System.Linq;

namespace PolyTraderSharp.Models
{
    public class AccountState
    {
        [Browsable(false)]
        public int AccountId { get; set; }

        [Category("01. General")]
        public string Name { get; set; } = string.Empty;

        [Category("02. Wallet & Keys")]
        public string WalletAddress { get; set; } = string.Empty;

        [Category("02. Wallet & Keys")]
        public string ApiKey { get; set; } = string.Empty;
        
        [Category("02. Wallet & Keys")]
        public string ApiSecret { get; set; } = string.Empty;

        [Category("02. Wallet & Keys")]
        public string ApiPassphrase { get; set; } = string.Empty;

        [Category("02. Wallet & Keys")]
        public string PrivateKey { get; set; } = string.Empty;

        [Category("01. General")]
        public bool IsDemo { get; set; }

        [Category("01. General")]
        public bool IsActive { get; set; } = true;

        [Category("01. General")]
        public bool CloseOnlyMode { get; set; } = false;

        [Category("03. Payouts")]
        public string PayoutAddress { get; set; } = string.Empty;
        
        [Category("03. Payouts")]
        public decimal PayoutLimitUsd { get; set; } = 0;

        // Balances
        [Browsable(false)]
        public decimal TotalBalance { get; set; }
        
        [Browsable(false)]
        public decimal AvailableBalance { get; set; }

        // Risk Settings
        // Copytrading-Detail-Einstellungen (PerMarketLimit, MaxBuyPrice, Zeit-Limits …)
        // liegen bewusst NICHT mehr hier, sondern im Copytrading-Modul
        // (CopyTradingAccountSettings), da sie modulspezifisch sind.

        [Browsable(false)]
        public ConcurrentDictionary<string, Position> OpenPositions { get; } = new(StringComparer.OrdinalIgnoreCase);

        [Browsable(false)]
        public bool HasOpenLimitOrders { get; set; } = false;

        public void UpdateBalance(decimal available)
        {
            AvailableBalance = available;
            decimal inPositions = OpenPositions.Values.Sum(p => (decimal)p.AmountUsd);
            TotalBalance = AvailableBalance + inPositions;
        }
    }
}
