package com.eactive.testmaster.queue.service;

import com.eactive.testmaster.queue.entity.QueueHandler;
import com.eactive.testmaster.queue.repository.QueueHandlerRepository;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class QueueHandlerService {

    @Autowired
    private QueueHandlerRepository queueHandlerRepository;

    @Autowired
    private DynamicQueueManager dynamicQueueManager;

    public void initAllQueues() {
        queueHandlerRepository.findAll().forEach(queueHandler -> {
            dynamicQueueManager.startQueueListener(queueHandler);
        });
    }


    public Page<QueueHandler> findAll(Specification<QueueHandler> specification, Pageable pageable) {
        return queueHandlerRepository.findAll(specification, pageable);
    }

    public QueueHandler findById(String id) {
        return queueHandlerRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("Queue Handler not found with id: " + id));
    }

    public QueueHandler create(QueueHandler queueHandler) {
        return queueHandlerRepository.save(queueHandler);
    }

    public QueueHandler update(String queueName, QueueHandler queueHandler) {
        QueueHandler handler = queueHandlerRepository.findById(queueName).orElseThrow(() -> new IllegalArgumentException("Queue Handler not found with name: " + queueName));
        handler.setHandlerScript(queueHandler.getHandlerScript());
        return queueHandlerRepository.save(handler);
    }

    public void deleteById(String id) {
        queueHandlerRepository.deleteById(id);
    }
}
