package com.aegis.resource.expert.domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.aegis.common.exception.ServiceException;

/**
 * 专家能力标签值对象
 * 
 * @author aegis
 */
public class ExpertCapability {
    
    private static final int MAX_SIZE = 10;
    private static final int MAX_LENGTH = 500;
    
    private final List<String> items;
    
    private ExpertCapability(List<String> items) {
        if (items == null) {
            items = new ArrayList<>();
        }
        // 业务规则：去重
        Set<String> unique = new LinkedHashSet<>(items);
        List<String> deduplicated = new ArrayList<>(unique);
        // 业务规则：数量限制
        if (deduplicated.size() > MAX_SIZE) {
            throw new ServiceException("能力标签不能超过" + MAX_SIZE + "项");
        }
        // 业务规则：每个项不能为空
        for (String item : deduplicated) {
            if (StringUtils.isBlank(item)) {
                throw new ServiceException("能力标签项不能为空");
            }
        }
        this.items = Collections.unmodifiableList(deduplicated);
    }
    
    /**
     * 创建专家能力标签值对象（允许空）
     */
    public static ExpertCapability of(List<String> items) {
        if (items == null || items.isEmpty()) {
            return empty();
        }
        return new ExpertCapability(items);
    }
    
    /**
     * 创建空的能力标签
     */
    public static ExpertCapability empty() {
        return new ExpertCapability(new ArrayList<>());
    }
    
    /**
     * 从存储格式创建（应用服务层使用）
     */
    public static ExpertCapability fromStorage(String storageFormat) {
        if (StringUtils.isBlank(storageFormat)) {
            return empty();
        }
        // 解析存储格式（JSON 或逗号分隔）
        List<String> items = parseStorageFormat(storageFormat);
        return items.isEmpty() ? empty() : new ExpertCapability(items);
    }
    
    /**
     * 转换为存储格式（供基础设施层使用）
     */
    public String toStorageFormat() {
        if (items.isEmpty()) {
            return null;
        }
        try {
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            String json = mapper.writeValueAsString(items);
            if (json.length() > MAX_LENGTH) {
                throw new ServiceException("能力标签长度不能超过" + MAX_LENGTH + "个字符");
            }
            return json;
        } catch (Exception e) {
            throw new ServiceException("能力标签序列化失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取能力项列表（不可变）
     */
    public List<String> getItems() {
        return items;
    }
    
    /**
     * 是否为空
     */
    public boolean isEmpty() {
        return items.isEmpty();
    }
    
    /**
     * 数量
     */
    public int size() {
        return items.size();
    }
    
    private static List<String> parseStorageFormat(String storageFormat) {
        // 尝试 JSON 格式
        if (storageFormat.trim().startsWith("[")) {
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                return mapper.readValue(storageFormat, new com.fasterxml.jackson.core.type.TypeReference<List<String>>() {});
            } catch (Exception e) {
                throw new ServiceException("能力标签格式错误: " + e.getMessage());
            }
        }
        // 兼容逗号分隔格式
        String[] parts = storageFormat.split(",");
        List<String> result = new ArrayList<>();
        for (String part : parts) {
            if (StringUtils.isNotBlank(part)) {
                result.add(part.trim());
            }
        }
        return result;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ExpertCapability that = (ExpertCapability) o;
        return Objects.equals(items, that.items);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(items);
    }
    
    @Override
    public String toString() {
        return "ExpertCapability" + items;
    }
}