using ClaudeDo.Data;
using ClaudeDo.Data.Repositories;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Worker.Services;

public sealed class StaleTaskRecovery : IHostedService
{
    private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
    private readonly ILogger<StaleTaskRecovery> _logger;

    public StaleTaskRecovery(IDbContextFactory<ClaudeDoDbContext> dbFactory, ILogger<StaleTaskRecovery> logger)
    {
        _dbFactory = dbFactory;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        using var context = _dbFactory.CreateDbContext();
        var tasks = new TaskRepository(context);
        var flipped = await tasks.FlipAllRunningToFailedAsync("worker restart", cancellationToken);
        if (flipped > 0)
            _logger.LogWarning("Stale task recovery: flipped {Count} running task(s) to failed", flipped);
        else
            _logger.LogInformation("Stale task recovery: no stale tasks found");
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
