package tech.easyflow.ai.documentimport.task;

import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * CSV 导入入口支持策略测试。
 */
public class CsvImportSupportPolicyTest {

    /**
     * 验证单文件、管理端批次和 Public API 批次三条入口都允许 CSV。
     *
     * @throws Exception 反射读取失败
     */
    @Test
    public void shouldAllowCsvAcrossAllKnowledgeImportEntrypoints()
        throws Exception {
        KnowledgeDocumentImportTaskAppService taskService =
            new KnowledgeDocumentImportTaskAppService();
        Method assertSupported = KnowledgeDocumentImportTaskAppService.class
            .getDeclaredMethod("assertSupportedImportFile", String.class);
        assertSupported.setAccessible(true);
        Method normalizeExtension =
            KnowledgeDocumentImportTaskAppService.class.getDeclaredMethod(
                "normalizeFileExtension", String.class, String.class);
        normalizeExtension.setAccessible(true);
        String lowerCaseExtension = (String) normalizeExtension.invoke(
            taskService, "results.csv", "/knowledge/results.csv");
        String upperCaseExtension = (String) normalizeExtension.invoke(
            taskService, "RESULTS.CSV", "/knowledge/RESULTS.CSV");
        Assert.assertEquals("csv", lowerCaseExtension);
        Assert.assertEquals("csv", upperCaseExtension);
        assertSupported.invoke(taskService, lowerCaseExtension);
        assertSupported.invoke(taskService, upperCaseExtension);

        Assert.assertTrue(readSupportedExtensions(
            DocumentImportBatchAppService.class).contains("csv"));
        Assert.assertTrue(readSupportedExtensions(
            KnowledgeImportBatchFacade.class).contains("csv"));
        Assert.assertSame(
            DocumentImportFormatPolicy.supportedExtensions(),
            readSupportedExtensions(DocumentImportBatchAppService.class));
        Assert.assertSame(
            DocumentImportFormatPolicy.supportedExtensions(),
            readSupportedExtensions(KnowledgeImportBatchFacade.class));
    }

    /**
     * 读取入口类的支持扩展名集合。
     *
     * @param type 入口类
     * @return 扩展名集合
     * @throws Exception 字段读取失败
     */
    @SuppressWarnings("unchecked")
    private Set<String> readSupportedExtensions(Class<?> type)
        throws Exception {
        Field field = type.getDeclaredField("SUPPORTED_EXTENSIONS");
        field.setAccessible(true);
        return (Set<String>) field.get(null);
    }
}
