using Microsoft.EntityFrameworkCore;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Infrastructure.Persistence;

namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Repositories;

/// <summary>
/// Project repository implementation using EF Core
/// </summary>
public class ProjectRepository(PMDbContext context) : IProjectRepository
{
    private readonly PMDbContext _context = context ?? throw new ArgumentNullException(nameof(context));

    public async Task<Project?> GetByIdAsync(ProjectId id, CancellationToken cancellationToken = default)
    {
        return await _context.Projects
            .Include(p => p.Epics)
            .FirstOrDefaultAsync(p => p.Id == id, cancellationToken);
    }

    public async Task<Project?> GetByKeyAsync(string key, CancellationToken cancellationToken = default)
    {
        return await _context.Projects
            .FirstOrDefaultAsync(p => p.Key.Value == key, cancellationToken);
    }

    public async Task<List<Project>> GetAllAsync(CancellationToken cancellationToken = default)
    {
        return await _context.Projects
            .OrderByDescending(p => p.CreatedAt)
            .ToListAsync(cancellationToken);
    }

    public async Task<Project?> GetProjectWithEpicAsync(EpicId epicId, CancellationToken cancellationToken = default)
    {
        return await _context.Projects
            .Include(p => p.Epics)
                .ThenInclude(e => e.Stories)
            .Where(p => p.Epics.Any(e => e.Id == epicId))
            .FirstOrDefaultAsync(cancellationToken);
    }

    public async Task<Project?> GetProjectWithStoryAsync(StoryId storyId, CancellationToken cancellationToken = default)
    {
        return await _context.Projects
            .Include(p => p.Epics)
                .ThenInclude(e => e.Stories)
                    .ThenInclude(s => s.Tasks)
            .Where(p => p.Epics.Any(e => e.Stories.Any(s => s.Id == storyId)))
            .FirstOrDefaultAsync(cancellationToken);
    }

    public async Task<Project?> GetProjectWithTaskAsync(TaskId taskId, CancellationToken cancellationToken = default)
    {
        return await _context.Projects
            .Include(p => p.Epics)
                .ThenInclude(e => e.Stories)
                    .ThenInclude(s => s.Tasks)
            .Where(p => p.Epics.Any(e => e.Stories.Any(s => s.Tasks.Any(t => t.Id == taskId))))
            .FirstOrDefaultAsync(cancellationToken);
    }

    public async Task AddAsync(Project project, CancellationToken cancellationToken = default)
    {
        await _context.Projects.AddAsync(project, cancellationToken);
    }

    public void Update(Project project)
    {
        _context.Projects.Update(project);
    }

    public void Delete(Project project)
    {
        _context.Projects.Remove(project);
    }
}
