using FluentAssertions;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Infrastructure.App.Repositories;
using TakeoutSaaS.Integration.Tests.Fixtures;

namespace TakeoutSaaS.Integration.Tests.App.Tenants;

public sealed class TenantAnnouncementRepositoryScopeTests
{
    [Fact]
    public async Task GivenTenantAndPlatformAnnouncements_WhenSearchAsync_ThenReturnsBoth()
    {
        // Arrange
        using var database = new SqliteTestDatabase();
        using var context = database.CreateContext(tenantId: 800);

        var tenantAnnouncement = CreateAnnouncement(tenantId: 800, id: 9200);
        var platformAnnouncement = CreateAnnouncement(tenantId: 0, id: 9201);

        context.TenantAnnouncements.AddRange(tenantAnnouncement, platformAnnouncement);
        await context.SaveChangesAsync();
        context.ChangeTracker.Clear();

        var repository = new EfTenantAnnouncementRepository(context);

        // Act
        var results = await repository.SearchAsync(
            tenantId: 800,
            keyword: null,
            status: null,
            type: null,
            isActive: null,
            effectiveFrom: null,
            effectiveTo: null,
            effectiveAt: null,
            cancellationToken: CancellationToken.None);

        // Assert
        results.Select(x => x.Id).Should().Contain(new[] { tenantAnnouncement.Id, platformAnnouncement.Id });
    }

    private static TenantAnnouncement CreateAnnouncement(long tenantId, long id)
        => new()
        {
            Id = id,
            TenantId = tenantId,
            Title = "公告",
            Content = "内容",
            AnnouncementType = TenantAnnouncementType.System,
            Priority = 1,
            EffectiveFrom = DateTime.UtcNow.AddMinutes(-5),
            PublisherScope = PublisherScope.Tenant,
            Status = AnnouncementStatus.Draft,
            TargetType = "ALL_TENANTS",
            RowVersion = new byte[] { 1 }
        };
}
