using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Tiku.Domain.Operations;
using Tiku.Domain.Tenancy;
using Tiku.Infrastructure.Persistence;
using Tiku.IntegrationTests.Api;

namespace Tiku.IntegrationTests;

public sealed class AuthorizationCachePersistenceTests
{
    [Fact]
    public async Task Rbac_mutation_bumps_durable_scope_version_and_enqueues_invalidation_in_same_save()
    {
        await using var factory = new ApiTestFactory();
        var tenantId = Guid.NewGuid();
        using var scope = factory.CreateSystemScope("Verify authorization version trigger");
        var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
        dbContext.Tenants.Add(new Tenant
        {
            Id = tenantId,
            Slug = tenantId.ToString("N"),
            Name = "Authorization cache trigger tenant"
        });
        dbContext.AuthorizationScopeVersions.Add(new AuthorizationScopeVersion
        {
            Realm = AuthRealm.Tenant,
            TenantId = tenantId
        });
        await dbContext.SaveChangesAsync();

        dbContext.TenantBackendRoles.Add(new TenantBackendRole
        {
            TenantId = tenantId,
            Code = "cache-trigger-role",
            Name = "Cache trigger role"
        });
        await dbContext.SaveChangesAsync();
        dbContext.ChangeTracker.Clear();

        var version = await dbContext.AuthorizationScopeVersions.AsNoTracking()
            .SingleAsync(item => item.TenantId == tenantId);
        Assert.Equal(2, version.Version);
        Assert.True(await dbContext.AuthorizationCacheInvalidations.AsNoTracking().AnyAsync(item =>
            item.TargetType == "scope" && item.TenantId == tenantId && item.Version == version.Version));
    }
}