using Microsoft.EntityFrameworkCore;
using Hua.Todo.Application.Data;
using Hua.Todo.Core.Entities;
using Hua.Todo.Core.Interfaces;

namespace Hua.Todo.Application.Repositories;

/// <summary>
/// 任务仓储实现（EF Core）。
/// </summary>
public class TaskRepository : ITaskRepository
{
    private readonly TodoDbContext _context;

    /// <summary>
    /// 创建 <see cref="TaskRepository"/>。
    /// </summary>
    /// <param name="context">数据库上下文。</param>
    public TaskRepository(TodoDbContext context)
    {
        _context = context;
    }

    /// <summary>
    /// 获取所有任务。
    /// </summary>
    /// <returns>包含所有任务实体的列表。</returns>
    public async Task<List<TaskEntity>> GetAllAsync()
    {
        return await _context.Tasks
            .Include(t => t.SubTasks)
            .ToListAsync();
    }

    /// <summary>
    /// 根据 ID 获取任务。
    /// </summary>
    /// <param name="id">任务 ID。</param>
    /// <returns>匹配的任务实体；如果不存在则返回 null。</returns>
    public async Task<TaskEntity?> GetByIdAsync(int id)
    {
        return await _context.Tasks
            .Include(t => t.SubTasks)
            .FirstOrDefaultAsync(t => t.Id == id);
    }

    /// <summary>
    /// 获取未完成任务列表。
    /// </summary>
    /// <returns>未完成的任务实体列表。</returns>
    public async Task<List<TaskEntity>> GetActiveTasksAsync()
    {
        return await _context.Tasks
            .Where(t => !t.IsCompleted)
            .OrderByDescending(t => t.CreatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 获取已完成任务列表。
    /// </summary>
    /// <returns>已完成的任务实体列表。</returns>
    public async Task<List<TaskEntity>> GetCompletedTasksAsync()
    {
        return await _context.Tasks
            .Where(t => t.IsCompleted)
            .OrderByDescending(t => t.UpdatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 新增一个任务。
    /// </summary>
    /// <param name="taskEntity">要添加的任务实体。</param>
    /// <returns>已持久化的任务实体（包含生成的 ID）。</returns>
    public async Task<TaskEntity> AddAsync(TaskEntity taskEntity)
    {
        _context.Tasks.Add(taskEntity);
        await _context.SaveChangesAsync();
        return taskEntity;
    }

    /// <summary>
    /// 更新现有任务信息。
    /// </summary>
    /// <param name="taskEntity">要更新的任务实体。</param>
    /// <returns>更新后的任务实体。</returns>
    public async Task<TaskEntity> UpdateAsync(TaskEntity taskEntity)
    {
        taskEntity.UpdatedAt = DateTime.UtcNow;
        _context.Tasks.Update(taskEntity);
        await _context.SaveChangesAsync();
        return taskEntity;
    }

    /// <summary>
    /// 根据 ID 删除任务。
    /// </summary>
    /// <param name="id">要删除的任务 ID。</param>
    /// <returns>表示删除操作的任务。</returns>
    public async Task DeleteAsync(int id)
    {
        var task = await _context.Tasks.FindAsync(id);
        if (task != null)
        {
            _context.Tasks.Remove(task);
            await _context.SaveChangesAsync();
        }
    }

    /// <summary>
    /// 获取指定父任务的子任务列表。
    /// </summary>
    /// <param name="parentTaskId">父任务 ID。</param>
    /// <returns>子任务实体的列表。</returns>
    public async Task<List<TaskEntity>> GetSubTasksAsync(int parentTaskId)
    {
        return await _context.Tasks
            .Where(t => t.ParentTaskId == parentTaskId)
            .OrderByDescending(t => t.CreatedAt)
            .ToListAsync();
    }
}
