using ClaudeDo.Data.Models;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Data.Repositories;

public sealed class TaskRunRepository
{
    private readonly ClaudeDoDbContext _context;

    public TaskRunRepository(ClaudeDoDbContext context) => _context = context;

    public async Task AddAsync(TaskRunEntity entity, CancellationToken ct = default)
    {
        _context.TaskRuns.Add(entity);
        await _context.SaveChangesAsync(ct);
    }

    public async Task UpdateAsync(TaskRunEntity entity, CancellationToken ct = default)
    {
        _context.TaskRuns.Update(entity);
        await _context.SaveChangesAsync(ct);
    }

    public async Task<TaskRunEntity?> GetByIdAsync(string id, CancellationToken ct = default)
    {
        return await _context.TaskRuns.FirstOrDefaultAsync(r => r.Id == id, ct);
    }

    public async Task<List<TaskRunEntity>> GetByTaskIdAsync(string taskId, CancellationToken ct = default)
    {
        return await _context.TaskRuns
            .Where(r => r.TaskId == taskId)
            .OrderBy(r => r.RunNumber)
            .ToListAsync(ct);
    }

    public async Task<TaskRunEntity?> GetLatestByTaskIdAsync(string taskId, CancellationToken ct = default)
    {
        return await _context.TaskRuns
            .Where(r => r.TaskId == taskId)
            .OrderByDescending(r => r.RunNumber)
            .FirstOrDefaultAsync(ct);
    }
}
