package com.qqchen.deploy.backend.notification.converter;

import com.qqchen.deploy.backend.framework.converter.BaseConverter;
import com.qqchen.deploy.backend.framework.utils.JsonUtils;
import com.qqchen.deploy.backend.notification.dto.NotificationTemplateDTO;
import com.qqchen.deploy.backend.notification.entity.NotificationTemplate;
import com.qqchen.deploy.backend.notification.entity.config.BaseTemplateConfig;
import com.qqchen.deploy.backend.notification.entity.config.EmailTemplateConfig;
import com.qqchen.deploy.backend.notification.entity.config.WeworkTemplateConfig;
import com.qqchen.deploy.backend.notification.enums.NotificationChannelTypeEnum;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import java.util.Map;

/**
 * 通知模板转换器
 *
 * @author qqchen
 * @since 2025-11-12
 */
@Mapper(componentModel = "spring")
public interface NotificationTemplateConverter extends BaseConverter<NotificationTemplate, NotificationTemplateDTO> {

    @Override
    @Mapping(target = "templateConfig", expression = "java(mapToTemplateConfig(entity.getTemplateConfig(), entity.getChannelType()))")
    @Mapping(target = "extraData", ignore = true)
    NotificationTemplateDTO toDto(NotificationTemplate entity);

    @Override
    @Mapping(target = "templateConfig", expression = "java(mapToTemplateConfigMap(dto.getTemplateConfig()))")
    NotificationTemplate toEntity(NotificationTemplateDTO dto);

    @Override
    @Mapping(target = "templateConfig", expression = "java(mapToTemplateConfigMap(dto.getTemplateConfig()))")
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "createTime", ignore = true)
    @Mapping(target = "updateTime", ignore = true)
    @Mapping(target = "createBy", ignore = true)
    @Mapping(target = "updateBy", ignore = true)
    @Mapping(target = "version", ignore = true)
    @Mapping(target = "deleted", ignore = true)
    void updateEntity(@org.mapstruct.MappingTarget NotificationTemplate entity, NotificationTemplateDTO dto);

    /**
     * 将Map转换为BaseTemplateConfig（根据渠道类型自动识别）
     */
    default BaseTemplateConfig mapToTemplateConfig(Map<String, Object> configMap, NotificationChannelTypeEnum channelType) {
        if (configMap == null || channelType == null) {
            return null;
        }
        
        return switch (channelType) {
            case WEWORK -> JsonUtils.fromMap(configMap, WeworkTemplateConfig.class);
            case EMAIL -> JsonUtils.fromMap(configMap, EmailTemplateConfig.class);
            default -> null;
        };
    }

    /**
     * 将BaseTemplateConfig转换为Map
     */
    default Map<String, Object> mapToTemplateConfigMap(BaseTemplateConfig config) {
        if (config == null) {
            return null;
        }
        return JsonUtils.toMap(config);
    }
}
