using ClaudeDo.Data;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Worker.Tests.Infrastructure;

public sealed class DbFixture : IDisposable
{
    public string DbPath { get; }

    public DbFixture()
    {
        DbPath = Path.Combine(Path.GetTempPath(), $"claudedo_test_{Guid.NewGuid():N}.db");
        // EnsureCreated uses the current model directly — no Designer.cs needed.
        using var ctx = CreateContext();
        ctx.Database.EnsureCreated();
    }

    public ClaudeDoDbContext CreateContext()
    {
        var options = new DbContextOptionsBuilder<ClaudeDoDbContext>()
            .UseSqlite($"Data Source={DbPath}")
            .Options;
        return new ClaudeDoDbContext(options);
    }

    public TestDbContextFactory CreateFactory() => new(this);

    public void Dispose()
    {
        try { File.Delete(DbPath); } catch { /* best effort */ }
        try { File.Delete(DbPath + "-wal"); } catch { }
        try { File.Delete(DbPath + "-shm"); } catch { }
    }
}

public sealed class TestDbContextFactory : IDbContextFactory<ClaudeDoDbContext>
{
    private readonly DbFixture _fixture;
    public TestDbContextFactory(DbFixture fixture) => _fixture = fixture;
    public ClaudeDoDbContext CreateDbContext() => _fixture.CreateContext();
}
