using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;

namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;

// Auth re-arch (C5): the SQL Server ApiKey entity and the repository's key methods
// (Add/Get/Update/Delete/GetApprovedKeysForMethod) were retired — inbound API keys
// now live in the shared ZB.MOM.WW.Auth.ApiKeys SQLite store. The former key
// round-trip, peppered-hasher, and ApprovedApiKeyIds CSV tests were removed with
// them; only the API-method catalogue remains here.
public class InboundApiRepositoryTests : IDisposable
{
    private readonly ScadaBridgeDbContext _context;
    private readonly InboundApiRepository _repository;

    public InboundApiRepositoryTests()
    {
        _context = SqliteTestHelper.CreateInMemoryContext();
        _repository = new InboundApiRepository(_context);
    }

    public void Dispose()
    {
        _context.Database.CloseConnection();
        _context.Dispose();
    }

    [Fact]
    public async Task AddApiMethod_AndGetByName_RoundTrips()
    {
        var method = new ApiMethod("DoThing", "return 1;");
        await _repository.AddApiMethodAsync(method);
        await _repository.SaveChangesAsync();

        var loaded = await _repository.GetMethodByNameAsync("DoThing");
        Assert.NotNull(loaded);
        Assert.Equal(method.Id, loaded!.Id);
    }

    [Fact]
    public async Task DeleteApiMethod_RemovesEntity()
    {
        var method = new ApiMethod("ToDelete", "return 1;");
        await _repository.AddApiMethodAsync(method);
        await _repository.SaveChangesAsync();

        await _repository.DeleteApiMethodAsync(method.Id);
        await _repository.SaveChangesAsync();

        Assert.Null(await _repository.GetApiMethodByIdAsync(method.Id));
    }

    [Fact]
    public void Constructor_NullContext_Throws()
    {
        Assert.Throws<ArgumentNullException>(() => new InboundApiRepository(null!));
    }
}
