using Microsoft.EntityFrameworkCore;
using TodoList.Application.Data;
using TodoList.Core.Entities;
using TodoList.Core.Interfaces;

namespace TodoList.Application.Repositories;

public class TaskRepository : ITaskRepository
{
    private readonly TodoDbContext _context;

    public TaskRepository(TodoDbContext context)
    {
        _context = context;
    }

    public async Task<List<TaskEntity>> GetAllAsync()
    {
        return await _context.Tasks
            .Include(t => t.SubTasks)
            .ToListAsync();
    }

    public async Task<TaskEntity?> GetByIdAsync(int id)
    {
        return await _context.Tasks
            .Include(t => t.SubTasks)
            .FirstOrDefaultAsync(t => t.Id == id);
    }

    public async Task<List<TaskEntity>> GetActiveTasksAsync()
    {
        return await _context.Tasks
            .Where(t => !t.IsCompleted)
            .OrderByDescending(t => t.CreatedAt)
            .ToListAsync();
    }

    public async Task<List<TaskEntity>> GetCompletedTasksAsync()
    {
        return await _context.Tasks
            .Where(t => t.IsCompleted)
            .OrderByDescending(t => t.UpdatedAt)
            .ToListAsync();
    }

    public async Task<TaskEntity> AddAsync(TaskEntity taskEntity)
    {
        _context.Tasks.Add(taskEntity);
        await _context.SaveChangesAsync();
        return taskEntity;
    }

    public async Task<TaskEntity> UpdateAsync(TaskEntity taskEntity)
    {
        taskEntity.UpdatedAt = DateTime.UtcNow;
        _context.Tasks.Update(taskEntity);
        await _context.SaveChangesAsync();
        return taskEntity;
    }

    public async Task DeleteAsync(int id)
    {
        var task = await _context.Tasks.FindAsync(id);
        if (task != null)
        {
            _context.Tasks.Remove(task);
            await _context.SaveChangesAsync();
        }
    }

    public async Task<List<TaskEntity>> GetSubTasksAsync(int parentTaskId)
    {
        return await _context.Tasks
            .Where(t => t.ParentTaskId == parentTaskId)
            .OrderByDescending(t => t.CreatedAt)
            .ToListAsync();
    }
}
