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

namespace Codex.Dal.QueryProviders;

/// <summary>
/// Queryable provider for listing agents with filtering, sorting, and pagination
/// </summary>
public class ListAgentsQueryableProvider(CodexDbContext dbContext)
    : IQueryableProviderOverride<ListAgentsQueryItem>
{
    public Task<IQueryable<ListAgentsQueryItem>> GetQueryableAsync(
        object query,
        CancellationToken cancellationToken = default)
    {
        var result = dbContext.Agents
            .AsNoTracking()
            .Where(a => !a.IsDeleted)
            .Select(a => new ListAgentsQueryItem
            {
                Id = a.Id,
                Name = a.Name,
                Description = a.Description,
                Type = a.Type,
                ModelProvider = a.ModelProvider,
                ModelName = a.ModelName,
                ProviderType = a.ProviderType,
                ModelEndpoint = a.ModelEndpoint,
                Status = a.Status,
                CreatedAt = a.CreatedAt,
                UpdatedAt = a.UpdatedAt,
                ToolCount = a.Tools.Count(t => t.IsEnabled),
                ExecutionCount = a.Executions.Count
            });

        return Task.FromResult(result);
    }
}
