using Microsoft.EntityFrameworkCore;
using OpenHarbor.CQRS.DynamicQuery.Abstractions;

namespace Codex.Dal.QueryProviders;

/// <summary>
/// Queryable provider for listing agent executions with filtering, sorting, and pagination
/// </summary>
public class ListAgentExecutionsQueryableProvider(CodexDbContext dbContext)
    : IQueryableProviderOverride<ListAgentExecutionsQueryItem>
{
    public Task<IQueryable<ListAgentExecutionsQueryItem>> GetQueryableAsync(
        object query,
        CancellationToken cancellationToken = default)
    {
        var result = dbContext.AgentExecutions
            .AsNoTracking()
            .Select(e => new ListAgentExecutionsQueryItem
            {
                Id = e.Id,
                AgentId = e.AgentId,
                AgentName = e.Agent.Name,
                ConversationId = e.ConversationId,
                // CA1845: Cannot use Span in EF Core expression trees
#pragma warning disable CA1845
                UserPrompt = e.UserPrompt.Length > 200
                    ? e.UserPrompt.Substring(0, 200) + "..."
                    : e.UserPrompt,
#pragma warning restore CA1845
                Status = e.Status,
                StartedAt = e.StartedAt,
                CompletedAt = e.CompletedAt,
                InputTokens = e.InputTokens ?? 0,
                OutputTokens = e.OutputTokens ?? 0,
                EstimatedCost = e.EstimatedCost ?? 0m,
                MessageCount = e.Messages.Count,
                ErrorMessage = e.ErrorMessage
            });

        return Task.FromResult(result);
    }
}
