package ru.soune.nocopy.service.referral;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import ru.soune.ReferralLevel;
import ru.soune.ReferralLevelProvider;
import ru.soune.nocopy.entity.referral.ReferralLevelEntity;
import ru.soune.nocopy.repository.ReferralLevelRepository;


import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class ReferralLevelProviderImpl implements ReferralLevelProvider {

    private final ReferralLevelRepository referralLevelRepository;

    @Override
    public List<ReferralLevel> getAvailableReferralLevels() {
        List<ReferralLevelEntity> entities = referralLevelRepository.findAll();

        return entities.stream()
                .map(this::createReferralLevel)
                .collect(Collectors.toList());
    }

    @Override
    public String getInitialReferralLevelId() {
        return "bronze";
    }

    @Override
    public ReferralLevel getReferralLevelById(String levelId) {
        return createReferralLevel(referralLevelRepository.findById(levelId));
    }

    private ReferralLevel createReferralLevel(ReferralLevelEntity entity) {
        return new ReferralLevel() {
            @Override
            public String getId() {
                return entity.getId();
            }

            @Override
            public String getName() {
                return entity.getName();
            }

            @Override
            public int getShare() {
                return entity.getRewardPercentage();
            }

            @Override
            public int getMinInvitee() {
                return entity.getMinInvitees();
            }

            @Override
            public int getMaxInvitee() {
                switch (entity.getId()) {
                    case "bronze": return 5;
                    case "silver": return 15;
                    case "gold": return 50;
                    case "platinum": return Integer.MAX_VALUE;
                    default: return Integer.MAX_VALUE;
                }
            }

            @Override
            public String getNext() {
                switch (entity.getId()) {
                    case "bronze": return "silver";
                    case "silver": return "gold";
                    case "gold": return "platinum";
                    default: return null;
                }
            }
        };
    }
}