namespace Brizco.Repository.Handlers.ShiftPlan;

public class CreateShiftPlanCommandHandler : IRequestHandler<CreateShiftPlanCommand, ShiftPlanLDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    public CreateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<ShiftPlanLDto> Handle(CreateShiftPlanCommand request, CancellationToken cancellationToken)
    {
        var shift = await _repositoryWrapper.SetRepository<Domain.Entities.Shift.Shift>()
            .TableNoTracking
            .FirstOrDefaultAsync(s => s.Id == request.ShiftId, cancellationToken);

        if (shift == null)
            throw new AppException("Shift not found", ApiResultStatusCode.NotFound);

        try
        {
            await _repositoryWrapper.BeginTransaction(cancellationToken);
            var shiftPlan = shift.AddPlan(request.StartAt, request.EndAt);

            if (request.UserIds.Count == 0)
                throw new AppException("شیفت بندی مورد نظر باید حداقل متشکل از یک فرد باشد",
                    ApiResultStatusCode.BadRequest);

            request.UserIds.ForEach(i => shiftPlan.AddUser(i));

            _repositoryWrapper.SetRepository<Domain.Entities.Shift.ShiftPlan>().Add(shiftPlan);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            await _repositoryWrapper.CommitAsync(cancellationToken);
            return shiftPlan.AdaptToLDto();
        }
        catch (Exception )
        {
            await _repositoryWrapper.RollBackAsync(cancellationToken);
            throw;
        }
    }
}