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.*;
import com.qqchen.deploy.backend.notification.entity.NotificationChannel;
import com.qqchen.deploy.backend.notification.entity.config.BaseNotificationConfig;
import com.qqchen.deploy.backend.notification.entity.config.EmailNotificationConfig;
import com.qqchen.deploy.backend.notification.entity.config.WeworkNotificationConfig;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import java.util.Map;

/**
 * 通知渠道转换器
 *
 * @author qqchen
 * @since 2025-10-22
 */
@Mapper(config = BaseConverter.class)
public abstract class NotificationChannelConverter implements BaseConverter<NotificationChannel, NotificationChannelDTO> {
    
    /**
     * Entity -> DTO
     * config: Map -> BaseNotificationConfig
     */
    @Override
    @Mapping(target = "config", expression = "java(mapToConfig(entity))")
    public abstract NotificationChannelDTO toDto(NotificationChannel entity);
    
    /**
     * DTO -> Entity
     * config: BaseNotificationConfig -> Map
     */
    @Override
    @Mapping(target = "config", expression = "java(mapToConfigMap(dto))")
    public abstract NotificationChannel toEntity(NotificationChannelDTO dto);
    
    /**
     * 更新Entity（手动实现）
     * config: BaseNotificationConfig -> Map
     */
    @Override
    public void updateEntity(NotificationChannel entity, NotificationChannelDTO dto) {
        if (entity == null || dto == null) {
            return;
        }
        
        // 更新基本字段
        entity.setName(dto.getName());
        entity.setChannelType(dto.getChannelType());
        entity.setEnabled(dto.getEnabled());
        entity.setDescription(dto.getDescription());
        
        // 更新config字段
        entity.setConfig(mapToConfigMap(dto));
    }
    
    /**
     * 将Entity的Map配置转换为Config对象
     */
    protected BaseNotificationConfig mapToConfig(NotificationChannel entity) {
        if (entity == null || entity.getConfig() == null) {
            return null;
        }
        
        // Map -> BaseNotificationConfig（根据渠道类型自动识别）
        return switch (entity.getChannelType()) {
            case WEWORK -> JsonUtils.fromMap(entity.getConfig(), WeworkNotificationConfig.class);
            case EMAIL -> JsonUtils.fromMap(entity.getConfig(), EmailNotificationConfig.class);
            default -> throw new IllegalArgumentException("不支持的渠道类型: " + entity.getChannelType());
        };
    }
    
    /**
     * 将Config对象转换为Entity的Map
     */
    protected Map<String, Object> mapToConfigMap(NotificationChannelDTO dto) {
        if (dto == null || dto.getConfig() == null) {
            return null;
        }
        
        // BaseNotificationConfig -> Map
        return JsonUtils.toMap(dto.getConfig());
    }
}

