using MediatR;
using Microsoft.EntityFrameworkCore;
using ColaFlow.Modules.ProjectManagement.Application.Common.Interfaces;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.Enums;

namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteSprint;

/// <summary>
/// Handler for DeleteSprintCommand
/// </summary>
public sealed class DeleteSprintCommandHandler(
    IApplicationDbContext context,
    IUnitOfWork unitOfWork)
    : IRequestHandler<DeleteSprintCommand, Unit>
{
    private readonly IApplicationDbContext _context = context ?? throw new ArgumentNullException(nameof(context));
    private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));

    public async Task<Unit> Handle(DeleteSprintCommand request, CancellationToken cancellationToken)
    {
        // Get sprint with tracking
        var sprintId = SprintId.From(request.SprintId);
        var sprint = await _context.Sprints
            .FirstOrDefaultAsync(s => s.Id == sprintId, cancellationToken);

        if (sprint == null)
            throw new NotFoundException("Sprint", request.SprintId);

        // Business rule: Cannot delete Active sprints
        if (sprint.Status.Name == SprintStatus.Active.Name)
            throw new DomainException("Cannot delete an active sprint. Please complete it first.");

        // Remove sprint
        _context.Sprints.Remove(sprint);

        // Save changes
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
