using DotNet.Testcontainers.Builders;
using JSMR.Tests.Fixtures;
using Testcontainers.MariaDb;

[assembly: AssemblyFixture(typeof(MariaDbContainerFixture))]

namespace JSMR.Tests.Fixtures;

public sealed class MariaDbContainerFixture : IAsyncLifetime
{
    const int MajorVersion = 10;
    const int MinorVersion = 11;
    const int Build = 6;

    private MariaDbContainer _container = default!;

    public string RootConnectionString { get; private set; } = default!;
    public string TemplateDbName { get; } = "jsmr_template";

    public async ValueTask InitializeAsync()
    {
        _container = new MariaDbBuilder($"mariadb:{MajorVersion}.{MinorVersion}.{Build}")
            //.WithImage($"mariadb:{MajorVersion}.{MinorVersion}.{Build}")
            .WithEnvironment("MARIADB_ROOT_PASSWORD", "rootpw")
            .WithUsername("root")
            .WithPassword("rootpw")
            .WithWaitStrategy(Wait.ForUnixContainer().UntilInternalTcpPortIsAvailable(3306))
            .Build();

        await _container.StartAsync();

        var hostOverride = Environment.GetEnvironmentVariable("TESTCONTAINERS_HOST_OVERRIDE");
        var host = string.IsNullOrWhiteSpace(hostOverride) ? "127.0.0.1" : hostOverride;

        RootConnectionString = _container.GetConnectionString()
            .Replace("127.0.0.1", host)      // normalize when running inside job container
            .Replace("localhost", host);

        // Build the template ONCE with EF + your existing seed
        await MariaDbClone.CreateTemplateAsync(
            RootConnectionString,
            TemplateDbName);
    }

    public async ValueTask DisposeAsync() => await _container.DisposeAsync();
}