package com.ruoyi.web.kb.support;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.ruoyi.common.exception.ServiceException;

@DisplayName("KbFileUrlResolver")
class KbFileUrlResolverTest
{
    @Test
    @DisplayName("外网域名改写为内网地址")
    void rewriteExtranetHost()
    {
        String url = "https://bqxm.alafarms.com/profile/2026/01/a.pdf";
        String resolved = KbFileUrlResolver.resolveForKbUpload(url, null);
        assertEquals("https://192.168.153.16:443/profile/2026/01/a.pdf", resolved);
    }

    @Test
    @DisplayName("不含外网域名时不改写")
    void noRewriteWhenHostAbsent()
    {
        String url = "https://other.example.com/file.pdf";
        assertEquals(url, KbFileUrlResolver.resolveForKbUpload(url, null));
    }

    @Test
    @DisplayName("相对路径拼接后按 contentFileUrl 是否含外网域名决定是否改写 base")
    void relativePathWithExtranetInContentUrl()
    {
        String content = "https://bqxm.alafarms.com/profile/a.pdf";
        assertEquals(
                "https://192.168.153.16:443/profile/a.pdf",
                KbFileUrlResolver.resolveForKbUpload(content, "https://ignored.example.com"));
    }

    @Test
    @DisplayName("相对路径且 base 含外网域名时改写拼接结果")
    void relativePathExtranetInBaseWhenContentContainsHost()
    {
        String content = "https://bqxm.alafarms.com/profile/a.pdf";
        // absolute URL path — already covered; test relative with marker in content
        String relativeContent = "/profile/b.pdf?from=bqxm.alafarms.com";
        String resolved = KbFileUrlResolver.resolveForKbUpload(
                relativeContent, "https://bqxm.alafarms.com");
        assertEquals("https://192.168.153.16:443/profile/b.pdf?from=bqxm.alafarms.com", resolved);
    }

    @Test
    @DisplayName("正文地址为空时抛错")
    void emptyUrlThrows()
    {
        assertThrows(ServiceException.class, () -> KbFileUrlResolver.resolveForKbUpload("", "http://base"));
    }
}
