package de.assecutor.votianlt.pages.service;

import de.assecutor.votianlt.model.TaskTemplate;
import de.assecutor.votianlt.model.task.BaseTask;
import de.assecutor.votianlt.repository.TaskTemplateRepository;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class TaskTemplateService {

    private final TaskTemplateRepository taskTemplateRepository;

    public TaskTemplateService(TaskTemplateRepository taskTemplateRepository) {
        this.taskTemplateRepository = taskTemplateRepository;
    }

    public List<TaskTemplate> findByUserId(ObjectId userId) {
        return taskTemplateRepository.findByUserIdOrderByTemplateNameAsc(userId);
    }

    public Optional<TaskTemplate> findByUserIdAndTemplateName(ObjectId userId, String templateName) {
        return taskTemplateRepository.findByUserIdAndTemplateName(userId, templateName);
    }

    public TaskTemplate save(TaskTemplate taskTemplate) {
        taskTemplate.updateTimestamp();
        return taskTemplateRepository.save(taskTemplate);
    }

    public TaskTemplate createTemplate(ObjectId userId, String templateName, List<BaseTask> tasks) {
        // Check if template with same name already exists for this user
        Optional<TaskTemplate> existing = findByUserIdAndTemplateName(userId, templateName);
        if (existing.isPresent()) {
            throw new RuntimeException("Template mit dem Namen '" + templateName + "' existiert bereits");
        }

        TaskTemplate template = new TaskTemplate();
        template.setUserId(userId);
        template.setTemplateName(templateName);
        template.setTasks(tasks);

        return save(template);
    }

    public void deleteByUserIdAndTemplateName(ObjectId userId, String templateName) {
        taskTemplateRepository.deleteByUserIdAndTemplateName(userId, templateName);
    }

    public boolean templateExists(ObjectId userId, String templateName) {
        return findByUserIdAndTemplateName(userId, templateName).isPresent();
    }
}