using TodoTask = TodoList.Core.Entities.Task;
using TodoList.Core.Entities;
using TodoList.Core.Interfaces;

namespace TodoList.Api.Services;

/// <summary>
/// 任务服务实现类，提供任务相关的业务逻辑
/// </summary>
public class TaskService : ITaskService
{
    private readonly ITaskRepository _repository;

    /// <summary>
    /// 构造函数，注入任务仓储
    /// </summary>
    /// <param name="repository">任务仓储接口</param>
    public TaskService(ITaskRepository repository)
    {
        _repository = repository;
    }

    /// <summary>
    /// 获取所有任务
    /// </summary>
    /// <returns>任务列表</returns>
    public async System.Threading.Tasks.Task<List<TodoTask>> GetAllTasksAsync()
    {
        return await _repository.GetAllAsync();
    }

    /// <summary>
    /// 根据ID获取指定任务
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>任务对象，如果不存在则返回null</returns>
    public async System.Threading.Tasks.Task<TodoTask?> GetTaskByIdAsync(int id)
    {
        return await _repository.GetByIdAsync(id);
    }

    /// <summary>
    /// 获取所有未完成的任务
    /// </summary>
    /// <returns>未完成任务列表</returns>
    public async System.Threading.Tasks.Task<List<TodoTask>> GetActiveTasksAsync()
    {
        return await _repository.GetActiveTasksAsync();
    }

    /// <summary>
    /// 获取所有已完成的任务
    /// </summary>
    /// <returns>已完成任务列表</returns>
    public async System.Threading.Tasks.Task<List<TodoTask>> GetCompletedTasksAsync()
    {
        return await _repository.GetCompletedTasksAsync();
    }

    /// <summary>
    /// 创建新任务
    /// </summary>
    /// <param name="title">任务标题</param>
    /// <param name="priority">任务优先级</param>
    /// <param name="parentTaskId">父任务ID（可选）</param>
    /// <returns>创建的任务对象</returns>
    /// <exception cref="ArgumentException">当任务标题为空时抛出</exception>
    public async System.Threading.Tasks.Task<TodoTask> CreateTaskAsync(string title, TaskPriority priority, int? parentTaskId = null)
    {
        if (string.IsNullOrWhiteSpace(title))
        {
            throw new ArgumentException("任务标题不能为空", nameof(title));
        }

        var task = new TodoTask
        {
            Title = title.Trim(),
            Priority = priority,
            IsCompleted = false,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow,
            ParentTaskId = parentTaskId
        };

        return await _repository.AddAsync(task);
    }

    /// <summary>
    /// 更新任务
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <param name="title">新的任务标题（可选）</param>
    /// <param name="priority">新的任务优先级（可选）</param>
    /// <returns>更新后的任务对象</returns>
    /// <exception cref="KeyNotFoundException">当任务不存在时抛出</exception>
    public async System.Threading.Tasks.Task<TodoTask> UpdateTaskAsync(int id, string? title = null, TaskPriority? priority = null)
    {
        var task = await _repository.GetByIdAsync(id);
        if (task == null)
        {
            throw new KeyNotFoundException($"未找到ID为 {id} 的任务");
        }

        if (!string.IsNullOrWhiteSpace(title))
        {
            task.Title = title.Trim();
        }

        if (priority.HasValue)
        {
            task.Priority = priority.Value;
        }

        return await _repository.UpdateAsync(task);
    }

    /// <summary>
    /// 切换任务的完成状态
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>更新后的任务对象</returns>
    /// <exception cref="KeyNotFoundException">当任务不存在时抛出</exception>
    public async System.Threading.Tasks.Task<TodoTask> ToggleCompleteAsync(int id)
    {
        var task = await _repository.GetByIdAsync(id);
        if (task == null)
        {
            throw new KeyNotFoundException($"未找到ID为 {id} 的任务");
        }

        task.IsCompleted = !task.IsCompleted;
        var updatedTask = await _repository.UpdateAsync(task);

        if (task.IsCompleted)
        {
            await MarkSubTasksCompletedAsync(id);
        }

        return updatedTask;
    }

    /// <summary>
    /// 递归标记所有子任务为已完成
    /// </summary>
    /// <param name="parentTaskId">父任务ID</param>
    private async System.Threading.Tasks.Task MarkSubTasksCompletedAsync(int parentTaskId)
    {
        var subTasks = await _repository.GetSubTasksAsync(parentTaskId);
        foreach (var subTask in subTasks)
        {
            if (!subTask.IsCompleted)
            {
                subTask.IsCompleted = true;
                await _repository.UpdateAsync(subTask);
                await MarkSubTasksCompletedAsync(subTask.Id);
            }
        }
    }

    /// <summary>
    /// 删除指定ID的任务
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <exception cref="KeyNotFoundException">当任务不存在时抛出</exception>
    public async System.Threading.Tasks.Task DeleteTaskAsync(int id)
    {
        var task = await _repository.GetByIdAsync(id);
        if (task == null)
        {
            throw new KeyNotFoundException($"未找到ID为 {id} 的任务");
        }

        await _repository.DeleteAsync(id);
    }

    /// <summary>
    /// 获取指定父任务的所有子任务
    /// </summary>
    /// <param name="parentTaskId">父任务ID</param>
    /// <returns>子任务列表</returns>
    public async System.Threading.Tasks.Task<List<TodoTask>> GetSubTasksAsync(int parentTaskId)
    {
        return await _repository.GetSubTasksAsync(parentTaskId);
    }
}
