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

namespace Nexus.Api.Repositories;

public sealed class TaskRepository(NexusDbContext db) : ITaskRepository
{
    public Task<List<WorkTask>> GetAllAsync(CancellationToken ct = default)
        => db.Tasks.AsNoTracking().OrderByDescending(x => x.UpdatedAt).ToListAsync(ct);

    public ValueTask<WorkTask?> GetByIdAsync(Guid id, CancellationToken ct = default)
        => db.Tasks.FindAsync([id], ct);

    public Task<List<WorkTask>> GetPendingApprovalAsync(CancellationToken ct = default)
    {
        var threshold = DateTimeOffset.UtcNow.AddHours(-1);
        return db.Tasks.AsNoTracking()
            .Where(x => x.State == TaskStateHelper.ToStateString(TaskState.InProgress) && x.UpdatedAt <= threshold)
            .OrderByDescending(x => x.UpdatedAt)
            .ToListAsync(ct);
    }

    public async Task<WorkTask> AddAsync(WorkTask task, CancellationToken ct = default)
    {
        db.Tasks.Add(task);
        await db.SaveChangesAsync(ct);
        return task;
    }

    public async Task UpdateAsync(WorkTask task, CancellationToken ct = default)
    {
        task.UpdatedAt = DateTimeOffset.UtcNow;
        db.Tasks.Update(task);
        await db.SaveChangesAsync(ct);
    }

    public async Task DeleteAsync(WorkTask task, CancellationToken ct = default)
    {
        db.Tasks.Remove(task);
        await db.SaveChangesAsync(ct);
    }

    public Task<int> CountAsync(CancellationToken ct = default)
        => db.Tasks.CountAsync(ct);

    public Task<int> CountByStateAsync(string state, CancellationToken ct = default)
        => db.Tasks.CountAsync(x => x.State == state, ct);

    public Task<WorkTask?> GetLastBlockedAsync(CancellationToken ct = default)
        => db.Tasks.AsNoTracking()
            .Where(x => x.State == TaskStateHelper.ToStateString(TaskState.Blocked))
            .OrderByDescending(x => x.UpdatedAt)
            .FirstOrDefaultAsync(ct);
}
