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

import com.qqchen.deploy.backend.deploy.dto.TeamEnvironmentNotificationConfigDTO;
import com.qqchen.deploy.backend.deploy.dto.UserTeamEnvironmentNotificationConfigDTO;
import com.qqchen.deploy.backend.deploy.entity.TeamEnvironmentNotificationConfig;
import com.qqchen.deploy.backend.framework.converter.BaseConverter;
import com.qqchen.deploy.backend.notification.entity.NotificationChannel;
import com.qqchen.deploy.backend.notification.entity.NotificationTemplate;
import org.mapstruct.Context;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import java.util.Map;
import java.util.Optional;

/**
 * 团队环境通知配置Converter
 *
 * @author qqchen
 * @since 2025-11-11
 */
@Mapper(componentModel = "spring")
public interface TeamEnvironmentNotificationConfigConverter 
        extends BaseConverter<TeamEnvironmentNotificationConfig, TeamEnvironmentNotificationConfigDTO> {

    /**
     * 转换为用户环境通知配置DTO（包含扩展字段）
     */
    @Mapping(target = "notificationChannelName", 
             expression = "java(getChannelName(config.getNotificationChannelId(), channelMap))")
    @Mapping(target = "preApprovalNotificationTemplateName", 
             expression = "java(getTemplateName(config.getPreApprovalNotificationTemplateId(), templateMap))")
    @Mapping(target = "buildNotificationTemplateName", 
             expression = "java(getTemplateName(config.getBuildNotificationTemplateId(), templateMap))")
    UserTeamEnvironmentNotificationConfigDTO toUserDTO(
        TeamEnvironmentNotificationConfig config,
        @Context Map<Long, NotificationChannel> channelMap,
        @Context Map<Long, NotificationTemplate> templateMap
    );

    /**
     * 获取渠道名称
     */
    default String getChannelName(Long channelId, Map<Long, NotificationChannel> channelMap) {
        return Optional.ofNullable(channelId)
                .map(channelMap::get)
                .map(NotificationChannel::getName)
                .orElse(null);
    }

    /**
     * 获取模板名称
     */
    default String getTemplateName(Long templateId, Map<Long, NotificationTemplate> templateMap) {
        return Optional.ofNullable(templateId)
                .map(templateMap::get)
                .map(NotificationTemplate::getName)
                .orElse(null);
    }
}
