using System.Text;
using Minint.Core.Models;
using Minint.Core.Services.Impl;
using Minint.Infrastructure.Export;

namespace Minint.Tests;

public class ExportTests
{
    [Fact]
    public void BmpExport_WritesValidBmp()
    {
        var exporter = new BmpExporter();
        var pixels = new uint[] { 0xFF_FF_00_00, 0xFF_00_FF_00, 0xFF_00_00_FF, 0xFF_FF_FF_FF };

        var ms = new MemoryStream();
        exporter.Export(ms, pixels, 2, 2);

        ms.Position = 0;
        byte[] data = ms.ToArray();

        Assert.True(data.Length > 0);
        Assert.Equal((byte)'B', data[0]);
        Assert.Equal((byte)'M', data[1]);

        int fileSize = BitConverter.ToInt32(data, 2);
        Assert.Equal(data.Length, fileSize);
    }

    [Fact]
    public void GifExport_WritesValidGif()
    {
        var exporter = new GifExporter();
        var frame1 = new uint[16]; // 4x4 transparent
        var frame2 = new uint[16];
        Array.Fill(frame2, 0xFF_FF_00_00u);

        var frames = new List<(uint[] Pixels, uint DelayMs)>
        {
            (frame1, 100),
            (frame2, 200),
        };

        var ms = new MemoryStream();
        exporter.Export(ms, frames, 4, 4);

        ms.Position = 0;
        byte[] data = ms.ToArray();

        Assert.True(data.Length > 0);
        string sig = Encoding.ASCII.GetString(data, 0, 6);
        Assert.Equal("GIF89a", sig);
        Assert.Equal(0x3B, data[^1]); // GIF trailer
    }

    [Fact]
    public void BmpExport_DimensionMismatch_Throws()
    {
        var exporter = new BmpExporter();
        var pixels = new uint[3]; // does not match 2x2

        Assert.Throws<ArgumentException>(() =>
        {
            var ms = new MemoryStream();
            exporter.Export(ms, pixels, 2, 2);
        });
    }
}
