using Microsoft.EntityFrameworkCore;
using WorkManagementTool.Data;
using WorkManagementTool.Data.Entities;

namespace WorkManagementTool.Services
{
    public class HomeworkService
    {
        private readonly ApplicationDbContext _context;

        public HomeworkService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<List<Homework>> GetPendingHomeworkCountAsync()
        {
            return await _context.Homeworks
                .Where(h => !h.IsCompleted)
                .ToListAsync();
        }

        public async Task<List<Homework>> GetAllHomeworksAsync()
        {
            return await _context.Homeworks.ToListAsync();
        }

        public async Task<List<Homework>> GetCompletedHomeworksAsync(int idSchoolSubject)
        {
            return await _context.Homeworks
                .Where(w => w.IsCompleted && w.SchoolSubject.Id == idSchoolSubject)
                .ToListAsync();
        }

        public async Task<List<Homework>> GetUncompletedHomeworkAsync(int idSchoolSubject)
        {
            return await _context.Homeworks
                .Where(w => !w.IsCompleted && w.SchoolSubject.Id == idSchoolSubject)
                .ToListAsync();
        }

        public async Task<Homework?> GetHomeworkByIdAsync(int id)
        {
            return await _context.Homeworks.FindAsync(id);
        }

        public async Task AddHomeworkAsync(Homework homework)
        {
            _context.Homeworks.Add(homework);
            await _context.SaveChangesAsync();
        }

        public async Task UpdateHomeworkAsync(Homework homework)
        {
            _context.Homeworks.Update(homework);
            await _context.SaveChangesAsync();
        }

        public async Task DeleteHomeworkAsync(int id)
        {
            var homework = await _context.Homeworks.FindAsync(id);
            if (homework != null)
            {
                _context.Homeworks.Remove(homework);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<bool> ToggleHomeworkStatusAsync(int id)
        {
            var homework = await _context.Homeworks.FindAsync(id);
            if (homework != null)
            {
                homework.IsCompleted = !homework.IsCompleted;
                await _context.SaveChangesAsync();
                return true;
            }
            return false;
        }
    }
}
