namespace OpenWarehouse.warehouse.api.Common.TaskManager;

public class TaskManager(ApplicationDbContext context, ILogger<TaskManager> logger) : ITaskManager
{
    public async Task<string?> GetTaskStatus(Guid id)
    {
        logger.LogInformation("Get status of task with id:{id}", id);

        var result = await context.TaskStatus
            .FirstOrDefaultAsync(status => status.TaskId == id);

        if (result == null)
        {
            logger.LogWarning("Task with id:{id} not found", id);
            return null;
        }

        return result.Status;
    }

    public async Task<bool?> CreateTask(Guid id, string? actorId)
    {
        logger.LogInformation("Creating new task with id {id}", id);
        var newTask = new TaskStatusTable()
        {
            TaskId = id,
            Actor = actorId,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow,
            Status = TaskStatus.Accepted.ToString()
        };

        context.TaskStatus.Add(newTask);

        var result = await context.SaveChangesAsync();

        return result > 0;
    }

    public async Task<bool> UpdateTaskStatus(Guid id, TaskStatus status)
    {
        logger.LogInformation("Updating task with id:{id} to status:{status}", id, status.ToString());
        var task = await context.TaskStatus
            .FirstOrDefaultAsync(q => q.TaskId == id);

        if (task == null)
        {
             logger.LogWarning("Task with id:{id} not found", id);
             return false;
        }

        task.Status = status.ToString();
        task.UpdatedAt = DateTime.UtcNow;

        return (await context.SaveChangesAsync()) > 0;
    }
}