using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Dictionary.Entities;
using TakeoutSaaS.Domain.Dictionary.Repositories;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;

namespace TakeoutSaaS.Infrastructure.Dictionary.Repositories;

/// <summary>
/// 缓存失效日志仓储实现。
/// </summary>
public sealed class CacheInvalidationLogRepository(DictionaryDbContext context) : ICacheInvalidationLogRepository
{
    /// <summary>
    /// 新增失效日志。
    /// </summary>
    public Task AddAsync(CacheInvalidationLog log, CancellationToken cancellationToken = default)
    {
        context.CacheInvalidationLogs.Add(log);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 分页查询失效日志。
    /// </summary>
    public async Task<(IReadOnlyList<CacheInvalidationLog> Items, int TotalCount)> GetPagedAsync(
        int page,
        int pageSize,
        DateTime? startDate,
        DateTime? endDate,
        CancellationToken cancellationToken = default)
    {
        var query = context.CacheInvalidationLogs.AsNoTracking();

        if (startDate.HasValue)
        {
            query = query.Where(log => log.Timestamp >= startDate.Value);
        }

        if (endDate.HasValue)
        {
            query = query.Where(log => log.Timestamp <= endDate.Value);
        }

        var total = await query.CountAsync(cancellationToken);
        var items = await query
            .OrderByDescending(log => log.Timestamp)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync(cancellationToken);

        return (items, total);
    }

    /// <summary>
    /// 保存变更。
    /// </summary>
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
        => context.SaveChangesAsync(cancellationToken);
}
