using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Infrastructure.App.Persistence;

namespace TakeoutSaaS.Infrastructure.App.Repositories;

/// <summary>
/// EF 公告已读仓储。
/// </summary>
public sealed class EfTenantAnnouncementReadRepository(TakeoutAppDbContext context) : ITenantAnnouncementReadRepository
{
    /// <inheritdoc />
    public Task<IReadOnlyList<TenantAnnouncementRead>> GetByAnnouncementAsync(long tenantId, long announcementId, CancellationToken cancellationToken = default)
    {
        return context.TenantAnnouncementReads.AsNoTracking()
            .Where(x => x.TenantId == tenantId && x.AnnouncementId == announcementId)
            .OrderBy(x => x.ReadAt)
            .ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<TenantAnnouncementRead>)t.Result, cancellationToken);
    }

    /// <inheritdoc />
    public Task<IReadOnlyList<TenantAnnouncementRead>> GetByAnnouncementAsync(long tenantId, IEnumerable<long> announcementIds, long? userId, CancellationToken cancellationToken = default)
    {
        var ids = announcementIds.Distinct().ToArray();
        if (ids.Length == 0)
        {
            return Task.FromResult<IReadOnlyList<TenantAnnouncementRead>>(Array.Empty<TenantAnnouncementRead>());
        }

        var query = context.TenantAnnouncementReads.AsNoTracking()
            .Where(x => x.TenantId == tenantId && ids.Contains(x.AnnouncementId));

        if (userId.HasValue)
        {
            query = query.Where(x => x.UserId == userId.Value);
        }
        else
        {
            query = query.Where(x => x.UserId == null);
        }

        return query
            .OrderByDescending(x => x.ReadAt)
            .ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<TenantAnnouncementRead>)t.Result, cancellationToken);
    }

    /// <inheritdoc />
    public Task<TenantAnnouncementRead?> FindAsync(long tenantId, long announcementId, long? userId, CancellationToken cancellationToken = default)
    {
        return context.TenantAnnouncementReads
            .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.AnnouncementId == announcementId && x.UserId == userId, cancellationToken);
    }

    /// <inheritdoc />
    public Task AddAsync(TenantAnnouncementRead record, CancellationToken cancellationToken = default)
    {
        return context.TenantAnnouncementReads.AddAsync(record, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return context.SaveChangesAsync(cancellationToken);
    }
}
