namespace Repository;

public interface IEmailMessageRepository : IBaseRepository<EmailMessage>
{
    Task<EmailMessage?> ExistsAsync(string md5);
    
    /// <summary>
    /// 分页获取邮件列表（游标分页）
    /// </summary>
    /// <param name="lastReceivedDate">上一页最后一条记录的接收时间</param>
    /// <param name="lastId">上一页最后一条记录的ID</param>
    /// <param name="pageSize">每页数量</param>
    /// <returns>邮件列表、最后接收时间和最后ID</returns>
    Task<(List<EmailMessage> list, DateTime? lastReceivedDate, long lastId)> GetPagedListAsync(DateTime? lastReceivedDate, long? lastId, int pageSize = 20);
    
    /// <summary>
    /// 获取总数
    /// </summary>
    Task<long> GetTotalCountAsync();
}

public class EmailMessageRepository(IFreeSql freeSql) : BaseRepository<EmailMessage>(freeSql), IEmailMessageRepository
{
    public async Task<EmailMessage?> ExistsAsync(string md5)
    {
        return await FreeSql.Select<EmailMessage>()
            .Where(e => e.Md5 == md5)
            .FirstAsync();
    }

    public async Task<(List<EmailMessage> list, DateTime? lastReceivedDate, long lastId)> GetPagedListAsync(DateTime? lastReceivedDate, long? lastId, int pageSize = 20)
    {
        var query = FreeSql.Select<EmailMessage>();
        
        // 如果提供了游标，则获取小于游标位置的记录
        if (lastReceivedDate.HasValue && lastId.HasValue)
        {
            query = query.Where(e => e.ReceivedDate < lastReceivedDate.Value || 
                                     (e.ReceivedDate == lastReceivedDate.Value && e.Id < lastId.Value));
        }
        
        var list = await query
            .OrderByDescending(e => e.ReceivedDate)
            .OrderByDescending(e => e.Id)
            .Page(1, pageSize)
            .ToListAsync();
        
        var lastRecord = list.Count > 0 ? list.Last() : null;
        return (list, lastRecord?.ReceivedDate, lastRecord?.Id ?? 0);
    }

    public async Task<long> GetTotalCountAsync()
    {
        return await FreeSql.Select<EmailMessage>().CountAsync();
    }
}