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 ExpertSpecialty {
    
    private static final int MAX_SIZE = 10;
    private static final int MAX_LENGTH = 500;
    
    private final List<String> items;
    
    private ExpertSpecialty(List<String> items) {
        if (items == null || items.isEmpty()) {
            throw new ServiceException("专长领域不能为空");
        }
        // 业务规则：去重
        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 ExpertSpecialty of(List<String> items) {
        return new ExpertSpecialty(items);
    }
    
    /**
     * 从存储格式创建（应用服务层使用）
     */
    public static ExpertSpecialty fromStorage(String storageFormat) {
        if (StringUtils.isBlank(storageFormat)) {
            throw new ServiceException("专长领域不能为空");
        }
        // 解析存储格式（JSON 或逗号分隔）
        List<String> items = parseStorageFormat(storageFormat);
        return new ExpertSpecialty(items);
    }
    
    /**
     * 转换为存储格式（供基础设施层使用）
     */
    public String toStorageFormat() {
        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;
        ExpertSpecialty that = (ExpertSpecialty) o;
        return Objects.equals(items, that.items);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(items);
    }
    
    @Override
    public String toString() {
        return "ExpertSpecialty" + items;
    }
}