package com.eactive.testmaster.loadtest.service;

import com.eactive.testmaster.loadtest.entity.LoadTest;
import com.eactive.testmaster.loadtest.repository.LoadTestRepository;
import java.util.List;
import java.util.UUID;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class LoadTestMgmtService {

    @Autowired
    LoadTestRepository loadTestRepository;

    public List<LoadTest> findAll() {
        return loadTestRepository.findAll();
    }

    public LoadTest createLoadTest(LoadTest loadTest) {
        loadTest.setId(UUID.randomUUID().toString());
        return loadTestRepository.save(loadTest);
    }

    public LoadTest updateLoadTest(String id, LoadTest updatedLoadTest) {
        return loadTestRepository.findById(id)
            .map(loadTest -> {
                loadTest.setName(updatedLoadTest.getName());
                loadTest.setDescription(updatedLoadTest.getDescription());
                loadTest.setScenario(updatedLoadTest.getScenario());
                loadTest.setThreadCount(updatedLoadTest.getThreadCount());
                loadTest.setLoopCount(updatedLoadTest.getLoopCount());
                loadTest.setRampUpTime(updatedLoadTest.getRampUpTime());
                loadTest.setDuration(updatedLoadTest.getDuration());
                loadTest.setTestData(updatedLoadTest.getTestData());

                return loadTestRepository.save(loadTest);
            }).orElseGet(() -> {
                // If the LoadTest with the given id doesn't exist, create a new one
                updatedLoadTest.setId(id);
                return loadTestRepository.save(updatedLoadTest);
            });
    }

    public void deleteLoadTest(String id) {
        loadTestRepository.deleteById(id);
    }

}

