using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using PolyTraderSharp.Models;

namespace PolyTrader.Core.Persistence.Ef
{
    /// <summary>
    /// EF-Implementierung des Entscheidungsjournals. Write ist bewusst fehlertolerant:
    /// ein Journal-/DB-Fehler darf den Geld-Pfad (Engine/Leiter) niemals brechen –
    /// er wird auf der Konsole gemeldet und verworfen.
    /// </summary>
    public class EfDecisionJournal : IDecisionJournal
    {
        private readonly IDbContextFactory<CoreDbContext> _factory;
        public EfDecisionJournal(IDbContextFactory<CoreDbContext> factory) => _factory = factory;

        public void Write(DecisionRecord record)
        {
            try
            {
                using var ctx = _factory.CreateDbContext();
                ctx.DecisionJournal.Add(record);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[DecisionJournal] Write fehlgeschlagen (ignoriert): {ex.Message}");
            }
        }

        public List<DecisionRecord> Query(Expression<Func<DecisionRecord, bool>> predicate, int limit = 1000)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.DecisionJournal.AsNoTracking()
                .Where(predicate)
                .OrderByDescending(r => r.Timestamp)
                .Take(limit)
                .ToList();
        }
    }

    /// <summary>EF-Implementierung des Order-Lifecycle-Logs (gleiche Robustheits-Garantie).</summary>
    public class EfOrderEventLog : IOrderEventLog
    {
        private readonly IDbContextFactory<CoreDbContext> _factory;
        public EfOrderEventLog(IDbContextFactory<CoreDbContext> factory) => _factory = factory;

        public void Write(OrderEventRecord record)
        {
            try
            {
                using var ctx = _factory.CreateDbContext();
                ctx.OrderEvents.Add(record);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[OrderEventLog] Write fehlgeschlagen (ignoriert): {ex.Message}");
            }
        }

        public List<OrderEventRecord> Query(Expression<Func<OrderEventRecord, bool>> predicate, int limit = 1000)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.OrderEvents.AsNoTracking()
                .Where(predicate)
                .OrderByDescending(r => r.Timestamp)
                .Take(limit)
                .ToList();
        }
    }
}
