using System;
using PolyTrader.Core.Trading;
using PolyTrader.Modules.ResolutionFarming.Models;

namespace PolyTrader.Modules.ResolutionFarming.Logic
{
    /// <summary>
    /// Reine Logik für den Positions-Abschluss bei Marktauflösung: baut aus einer offenen Position und
    /// dem Ergebnis (Gewinner/Verlierer) den <see cref="RfClosedTrade"/> inkl. realisiertem PnL und Fees.
    /// </summary>
    public static class FarmingResolution
    {
        public static RfClosedTrade BuildClosedTrade(RfPosition p, bool isWinner, DateTime closedAt)
        {
            decimal exitPrice = isWinner ? 1.0m : 0.0m;
            decimal realizedPnl = FarmingFillModel.ResolvePnl(p.Size, p.EntryPrice, p.EntryFeeBps, isWinner);
            decimal entryCost = p.Size * p.EntryPrice;
            decimal fees = FeeModel.FeeUsd(entryCost, p.EntryFeeBps);   // Entry-Fee; die Auszahlung bei Resolution ist fee-frei

            return new RfClosedTrade
            {
                AccountId = p.AccountId,
                IsDemo = p.IsDemo,
                TokenId = p.TokenId,
                MarketSlug = p.MarketSlug,
                MarketQuestion = p.MarketQuestion,
                Outcome = p.Outcome,
                Category = p.Category,
                ClusterKey = p.ClusterKey,
                EntryPrice = p.EntryPrice,
                ExitPrice = exitPrice,
                Size = p.Size,
                RealizedPnl = realizedPnl,
                PnlPercent = p.AmountUsd > 0m ? realizedPnl / p.AmountUsd * 100m : 0m,
                TotalFees = fees,
                OpenedAt = p.OpenedAt,
                ClosedAt = closedAt,
                ExitReason = "Market Resolved",
                RedeemStatus = isWinner ? "Pending" : "None"   // Gewinner müssen (on-chain) redeemt werden
            };
        }
    }
}
