package com.qqchen.deploy.backend.workflow.entity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qqchen.deploy.backend.workflow.enums.WorkflowTriggerTypeEnum;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import org.springframework.util.StringUtils;

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

@Converter
public class WorkflowTriggerTypeListConverter implements AttributeConverter<List<WorkflowTriggerTypeEnum>, String> {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<WorkflowTriggerTypeEnum> attribute) {
        try {
            return objectMapper.writeValueAsString(
                attribute.stream()
                    .map(Enum::name)
                    .collect(Collectors.toList())
            );
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Error converting trigger type list to JSON", e);
        }
    }

    @Override
    public List<WorkflowTriggerTypeEnum> convertToEntityAttribute(String dbData) {
        try {
            if (StringUtils.isEmpty(dbData)) {
                return new ArrayList<>();
            }
            List<String> triggerNames = objectMapper.readValue(dbData, new TypeReference<List<String>>() {
            });
            return triggerNames.stream()
                .map(WorkflowTriggerTypeEnum::valueOf)
                .collect(Collectors.toList());
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Error converting JSON to trigger type list", e);
        }
    }
}