using Hua.Todo.Application.Interfaces;
using Hua.Todo.Application.Models;
using Hua.Todo.Core.Entities;
using Hua.Todo.Core.Interfaces;

namespace Hua.Todo.Application.Services;

/// <summary>
/// 任务管理服务实现
/// </summary>
public class TaskService : ITaskService
{
    private readonly ITaskRepository _taskRepository;

    /// <summary>
    /// 初始化任务管理服务的新实例
    /// </summary>
    /// <param name="taskRepository">任务仓储接口</param>
    public TaskService(ITaskRepository taskRepository)
    {
        _taskRepository = taskRepository;
    }

    /// <summary>
    /// 获取所有任务
    /// </summary>
    /// <returns>所有任务的 DTO 列表</returns>
    public async Task<List<TaskDto>> GetAllTasksAsync()
    {
        var tasks = await _taskRepository.GetAllAsync();
        return tasks.Select(MapToDto).ToList();
    }

    /// <summary>
    /// 根据 ID 获取任务详情
    /// </summary>
    /// <param name="id">任务 ID</param>
    /// <returns>找到的任务 DTO，如果不存在则返回 null</returns>
    public async Task<TaskDto?> GetTaskByIdAsync(int id)
    {
        var task = await _taskRepository.GetByIdAsync(id);
        return task != null ? MapToDto(task) : null;
    }

    /// <summary>
    /// 获取所有未完成的任务
    /// </summary>
    /// <returns>未完成任务的 DTO 列表</returns>
    public async Task<List<TaskDto>> GetActiveTasksAsync()
    {
        var allTasks = await _taskRepository.GetAllAsync();
        return allTasks.Where(t => !t.IsCompleted).Select(MapToDto).ToList();
    }

    /// <summary>
    /// 获取所有已完成的任务
    /// </summary>
    /// <returns>已完成任务的 DTO 列表</returns>
    public async Task<List<TaskDto>> GetCompletedTasksAsync()
    {
        var allTasks = await _taskRepository.GetAllAsync();
        return allTasks.Where(t => t.IsCompleted).Select(MapToDto).ToList();
    }

    /// <summary>
    /// 创建新任务
    /// </summary>
    /// <param name="dto">任务创建 DTO</param>
    /// <returns>新创建的任务 DTO</returns>
    public async Task<TaskDto> CreateTaskAsync(CreateTaskDto dto)
    {
        var task = new TaskEntity
        {
            Title = dto.Title,
            Priority = dto.Priority,
            IsCompleted = false,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow,
            ParentTaskId = dto.ParentTaskId
        };

        var createdTask = await _taskRepository.AddAsync(task);
        return MapToDto(createdTask);
    }

    /// <summary>
    /// 更新现有任务
    /// </summary>
    /// <param name="dto">包含更新内容的 DTO</param>
    /// <returns>更新后的任务 DTO</returns>
    /// <exception cref="KeyNotFoundException">当任务 ID 不存在时抛出</exception>
    public async Task<TaskDto> UpdateTaskAsync(UpdateTaskDto dto)
    {
        var task = await _taskRepository.GetByIdAsync(dto.Id);
        if (task == null)
        {
            throw new KeyNotFoundException($"Task with ID {dto.Id} not found");
        }

        if (!string.IsNullOrEmpty(dto.Title))
        {
            task.Title = dto.Title;
        }

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

        task.UpdatedAt = DateTime.UtcNow;

        var updatedTask = await _taskRepository.UpdateAsync(task);
        return MapToDto(updatedTask);
    }

    /// <summary>
    /// 切换任务的完成状态
    /// </summary>
    /// <param name="id">任务 ID</param>
    /// <returns>状态切换后的任务 DTO</returns>
    /// <exception cref="KeyNotFoundException">当任务 ID 不存在时抛出</exception>
    public async Task<TaskDto> ToggleCompleteAsync(int id)
    {
        var task = await _taskRepository.GetByIdAsync(id);
        if (task == null)
        {
            throw new KeyNotFoundException($"Task with ID {id} not found");
        }

        task.IsCompleted = !task.IsCompleted;
        task.UpdatedAt = DateTime.UtcNow;

        var updatedTask = await _taskRepository.UpdateAsync(task);
        return MapToDto(updatedTask);
    }

    /// <summary>
    /// 删除指定 ID 的任务
    /// </summary>
    /// <param name="id">任务 ID</param>
    /// <exception cref="KeyNotFoundException">当任务 ID 不存在时抛出</exception>
    public async Task DeleteTaskAsync(int id)
    {
        var task = await _taskRepository.GetByIdAsync(id);
        if (task == null)
        {
            throw new KeyNotFoundException($"Task with ID {id} not found");
        }

        await _taskRepository.DeleteAsync(id);
    }

    /// <summary>
    /// 获取指定父任务的所有子任务
    /// </summary>
    /// <param name="parentTaskId">父任务 ID</param>
    /// <returns>子任务的 DTO 列表</returns>
    public async Task<List<TaskDto>> GetSubTasksAsync(int parentTaskId)
    {
        var allTasks = await _taskRepository.GetAllAsync();
        return allTasks.Where(t => t.ParentTaskId == parentTaskId).Select(MapToDto).ToList();
    }

    /// <summary>
    /// 实体转 DTO 映射方法
    /// </summary>
    private TaskDto MapToDto(TaskEntity task)
    {
        return new TaskDto
        {
            Id = task.Id,
            Title = task.Title,
            Priority = task.Priority,
            IsCompleted = task.IsCompleted,
            CreatedAt = task.CreatedAt,
            UpdatedAt = task.UpdatedAt,
            ParentTaskId = task.ParentTaskId,
            SubTasks = task.SubTasks.Select(MapToDto).ToList()
        };
    }
}
