package com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.factory;

import com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.factory.dto.DocGenerationRequest;
import com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.factory.support.DocGenerator;
import com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.factory.support.SupportableDocGenerator;
import com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.wrapper.DocGeneratorWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@RequiredArgsConstructor
public class DocGeneratorFactory {

    private final Map<String, DocGenerator> docGenerators = new ConcurrentHashMap<>();

    private final List<SupportableDocGenerator> factories;

    public DocGenerator getGenerator(DocGenerationRequest request) {
        return docGenerators.computeIfAbsent(this.buildCacheKey(request), k ->
                new DocGeneratorWrapper(
                        factories.stream()
                                .filter(s -> s.support(request.getEquipList(), request.getEquCategory(), request.getEquDefine()))
                                .findFirst()
                                .orElseThrow(() -> new UnsupportedOperationException(String.format("No generator found for type: %s (list=%s, define=%s)",
                                        request.getEquipList(), request.getEquCategory(), request.getEquDefine()))))
        );
    }

    private String buildCacheKey(DocGenerationRequest request) {
        return String.join("|", request.getEquipList(), String.valueOf(request.getEquCategory()), String.valueOf(request.getEquDefine()));
    }
}
