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

namespace TakeoutSaaS.Infrastructure.Logs.Repositories;

/// <summary>
/// 运营操作日志仓储实现。
/// </summary>
public sealed class EfOperationLogRepository(TakeoutLogsDbContext logsContext) : IOperationLogRepository
{
    /// <inheritdoc />
    public async Task<(IReadOnlyList<OperationLog> Items, int Total)> SearchByOperatorPagedAsync(
        long tenantId,
        string operatorId,
        DateTime from,
        DateTime to,
        int page,
        int pageSize,
        CancellationToken cancellationToken = default)
    {
        // 1. 归一化参数
        var normalizedOperatorId = operatorId.Trim();
        var normalizedPage = page <= 0 ? 1 : page;
        var normalizedPageSize = pageSize <= 0 ? 50 : pageSize;

        // 2. 构建查询（操作人 + 时间窗 + 租户约束）
        var query = logsContext.OperationLogs
            .AsNoTracking()
            .Where(x => x.DeletedAt == null
                        && x.OperatorId == normalizedOperatorId
                        && x.CreatedAt >= from
                        && x.CreatedAt <= to
                        && x.Parameters != null
                        && (EF.Functions.ILike(x.Parameters, $"%\"tenantId\":{tenantId}%")
                            || EF.Functions.ILike(x.Parameters, $"%\"TenantId\":{tenantId}%")));

        // 3. 查询总数与分页项
        var total = await query.CountAsync(cancellationToken);
        var items = await query
            .OrderByDescending(x => x.CreatedAt)
            .Skip((normalizedPage - 1) * normalizedPageSize)
            .Take(normalizedPageSize)
            .ToListAsync(cancellationToken);

        // 4. 返回分页结果
        return (items, total);
    }

    /// <inheritdoc />
    public Task AddAsync(OperationLog log, CancellationToken cancellationToken = default)
    {
        // 1. 添加日志实体
        logsContext.OperationLogs.Add(log);
        // 2. 返回完成任务
        return Task.CompletedTask;
    }

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