using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Predictalytics.Domain.Entities;
using Predictalytics.Domain.Enums;
using Predictalytics.Infrastructure.Data;
using Predictalytics.Infrastructure.Data.Repositories;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;

namespace Predictalytics.Application.Tests.Services;

public class TradeRepositoryTests
{
    [Fact]
    public async Task AddRangeAsync_GeneratesCorrectSqlAndParameters()
    {
        using var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlite(connection)
            .Options;

        using var db = new AppDbContext(options);
        db.Database.EnsureCreated();

        var repo = new TradeRepository(db, NullLogger<TradeRepository>.Instance);

        var trade = new Trade
        {
            PlatformTradeId = "test_tx_usdc",
            MarketId = "cond_1",
            AssetId = "asset_1",
            Outcome = "Yes",
            Side = TradeSide.Buy,
            Price = 0.50m,
            Size = 100m,
            Amount = 50m,
            ExecutedAt = DateTime.UtcNow,
            UsdcSize = 123.45m,
            OutcomeIndex = 1
        };

        // SQLite will throw due to MySql specific "ON DUPLICATE KEY UPDATE" syntax.
        // We catch it and verify that it failed at execution rather than mapping/parameter building.
        var exception = await Assert.ThrowsAnyAsync<Exception>(() => repo.AddRangeAsync(new[] { trade }));
        
        // Assert that the exception is a syntax error near "DUPLICATE", which verifies the query was correctly built and sent
        Assert.Contains("DUPLICATE", exception.Message, StringComparison.OrdinalIgnoreCase);
    }
}
