namespace Brizco.Repository.Handlers.Positions;

public class UpdatePositionCommandHandler : IRequestHandler<UpdatePositionCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }

    public async Task<bool> Handle(UpdatePositionCommand request, CancellationToken cancellationToken)
    {
        var ent = await _repositoryWrapper.SetRepository<Position>()
            .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Postion not found", ApiResultStatusCode.NotFound);

        if (_currentUserService.ComplexId == null)
            throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
        if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
            throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);

        var newPosition = Position.Create(request.Title,
            request.Description,
            complexId,
            request.SectionId);
        newPosition.Id = request.Id;
        newPosition.CreatedAt = ent.CreatedAt;
        newPosition.CreatedBy = ent.CreatedBy;

        var permissionsDb = await _repositoryWrapper.SetRepository<PositionPermission>()
            .TableNoTracking
            .Where(f => f.PositionId == ent.Id)
            .ToListAsync(cancellationToken);

        foreach (var permissionDb in permissionsDb.Where(p=>!request.Permissions.Contains(p.Permission)))
        {
            _repositoryWrapper.SetRepository<PositionPermission>()
                .Delete(permissionDb);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        }

        foreach (var permission in request.Permissions.Where(p => !permissionsDb.Select(d => d.Permission).Contains(p)))
            newPosition.AddPermission(permission);

        _repositoryWrapper.SetRepository<Position>()
            .Update(newPosition);

        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        return true;
    }
}