using Microsoft.EntityFrameworkCore;
using Nexus.Api.Data;

namespace Nexus.Api.Repositories;

public sealed class ActivityRepository(NexusDbContext db) : IActivityRepository
{
    public Task<List<ActivityEvent>> GetRecentAsync(int take, CancellationToken ct = default)
        => db.Activity.AsNoTracking().OrderByDescending(x => x.CreatedAt).Take(take).ToListAsync(ct);

    public async Task<(List<ActivityEvent> Items, int TotalCount)> GetPagedAsync(
        string? type, string? sort, int page, int pageSize, CancellationToken ct = default)
    {
        var query = db.Activity.AsNoTracking();

        if (!string.IsNullOrWhiteSpace(type))
            query = query.Where(x => x.Type == type);

        query = (sort?.ToLowerInvariant()) switch
        {
            "oldest" => query.OrderBy(x => x.CreatedAt),
            _ => query.OrderByDescending(x => x.CreatedAt)
        };

        var totalCount = await query.CountAsync(ct);
        var items = await query.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct);
        return (items, totalCount);
    }

    public Task<List<ActivityEvent>> GetByAgentAsync(string agentId, int take, CancellationToken ct = default)
        => db.Activity.AsNoTracking()
            .Where(x => x.Message.Contains(agentId, StringComparison.OrdinalIgnoreCase) || x.Type == "agent")
            .OrderByDescending(x => x.CreatedAt)
            .Take(take)
            .ToListAsync(ct);

    public async Task<ActivityEvent> AddAsync(ActivityEvent activity, CancellationToken ct = default)
    {
        db.Activity.Add(activity);
        await db.SaveChangesAsync(ct);
        return activity;
    }
}
