using MaBibli.Api.Data;
using MaBibli.Api.Services.Catalogue;
using MaBibli.Shared.Textes;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

namespace MaBibli.Tests;

public sealed class ServiceBibliographieMasquageTests : IDisposable
{
    private readonly SqliteConnection _connexion = new("Data Source=:memory:");
    private readonly MaBibliDbContext _db;
    private readonly ServiceBibliographie _service;

    public ServiceBibliographieMasquageTests()
    {
        _connexion.Open();
        var options = new DbContextOptionsBuilder<MaBibliDbContext>()
            .UseSqlite(_connexion)
            .Options;
        _db = new MaBibliDbContext(options);
        _db.Database.EnsureCreated();
        _service = new ServiceBibliographie(_db, null!, new ServiceAuteurs(_db));
    }

    [Fact]
    public async Task Le_masquage_est_personnel_et_idempotent()
    {
        const int auteurId = 42;

        Assert.True(await _service.MasquerAsync(auteurId, "L'Œuvre", "mathieu"));
        Assert.True(await _service.MasquerAsync(auteurId, "L'oeuvre", "mathieu"));

        var ligne = await _db.BibliographiesMasquees.SingleAsync();
        Assert.Equal(CleOeuvre.Cle("L'Œuvre"), ligne.TitreNormalise);
        Assert.False(await _service.DemasquerAsync(auteurId, "L'Œuvre", "camille"));
        Assert.True(await _service.DemasquerAsync(auteurId, "L'oeuvre", "mathieu"));
        Assert.Empty(await _db.BibliographiesMasquees.ToListAsync());
    }

    public void Dispose()
    {
        _db.Dispose();
        _connexion.Dispose();
    }
}
