package com.eactive.kakao.rolling;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.jpa.AbstractDataService;

@Service
@Transactional
public class RollingSuffixService extends AbstractDataService<RollingSuffix, Long, RollingSuffixRepository> {

	@Autowired
    private CurrentCommitIdRepository currentCommitIdRepository;

    public String getCurrentSuffixByCommitId(String currentCommitId) {
		return repository
				.findOne(QRollingSuffix.rollingSuffix.commitId.eq(currentCommitId))
				.map(r -> r.getSuffix())
				.orElseThrow(() -> new EntityNotFoundException("commit id를 찾을 수 없습니다 : " + currentCommitId));
	}

    public void insertRollingSuffixAndUpdateCurrentCommitId(String newCommitId) {
        RollingSuffix newRollingSuffix = createNewRollingSuffix(newCommitId);
        RollingSuffix savedRollingSuffix = repository.save(newRollingSuffix);
        updateCurrentCommitId(savedRollingSuffix);
    }

    private RollingSuffix createNewRollingSuffix(String commitId) {
        RollingSuffix lastRollingSuffix = repository.findTopByOrderByIdDesc().orElse(new RollingSuffix());
        String newSuffix = calculateNextSuffix(lastRollingSuffix.getSuffix());

        RollingSuffix newRollingSuffix = new RollingSuffix();
        newRollingSuffix.setSuffix(newSuffix);
        newRollingSuffix.setCommitId(commitId);
        return newRollingSuffix;
    }

    private void updateCurrentCommitId(RollingSuffix rollingSuffix) {
        CurrentCommitId currentCommitId = currentCommitIdRepository.findById(CurrentCommitId.CURRENT_COMMIT_ID_ID)
                .orElseThrow(() -> new RuntimeException("CurrentCommitId not found"));
        currentCommitId.setRollingSuffix(rollingSuffix);
        currentCommitIdRepository.save(currentCommitId);
    }

    private String calculateNextSuffix(String lastSuffix) {
        int suffixNumber = (lastSuffix == null || lastSuffix.isEmpty()) ? 0 : Integer.parseInt(lastSuffix.replace("_", ""));
        return String.format("_%02d", (suffixNumber % 5) + 1);
    }
    
    public String insertRollingSuffix(String newCommitId) {
        RollingSuffix newRollingSuffix = createNewRollingSuffix(newCommitId);
        return repository.save(newRollingSuffix).getSuffix();
    }
    
    public void changeCurrentCommitId(String commitId) {
    	RollingSuffix targetRollingSuffix = repository.findOne(QRollingSuffix.rollingSuffix.commitId.eq(commitId))
    			.orElseThrow(() -> new EntityNotFoundException("RollingSuffix not found with commitId: " + commitId));
    	updateCurrentCommitId(targetRollingSuffix);
    }
}
