package com.mosquito.project.service;

import com.mosquito.project.config.AppConfig;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

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

class ShareConfigServiceTest {

    @Test
    void buildShareUrl_fallsBackToDefaultTemplateAndEncodesExtraParams() {
        AppConfig appConfig = new AppConfig();
        AppConfig.ShortLinkConfig shortLinkConfig = new AppConfig.ShortLinkConfig();
        shortLinkConfig.setLandingBaseUrl("https://example.com/landing");
        shortLinkConfig.setCdnBaseUrl("https://cdn.example.com");
        appConfig.setShortLink(shortLinkConfig);

        ShareConfigService service = new ShareConfigService(appConfig);

        Map<String, String> extraParams = new HashMap<>();
        extraParams.put("channel", "summer promo");
        extraParams.put("source", "email");

        String url = service.buildShareUrl(100L, 200L, "missing-template", extraParams);

        assertTrue(url.startsWith("https://example.com/landing?"));
        assertTrue(url.contains("activityId=100"));
        assertTrue(url.contains("inviter=200"));
        assertTrue(url.contains("channel=summer+promo"));
        assertTrue(url.contains("source=email"));
    }

    @Test
    void getShareMeta_resolvesPlaceholdersAndUsesTemplate() {
        AppConfig appConfig = new AppConfig();
        AppConfig.ShortLinkConfig shortLinkConfig = new AppConfig.ShortLinkConfig();
        shortLinkConfig.setLandingBaseUrl("https://example.com/landing");
        shortLinkConfig.setCdnBaseUrl("https://cdn.example.com");
        appConfig.setShortLink(shortLinkConfig);

        ShareConfigService service = new ShareConfigService(appConfig);
        ShareConfigService.ShareTemplate template = new ShareConfigService.ShareTemplate();
        template.setTitle("活动{{activityId}}");
        template.setDescription("邀请用户{{userId}}参与");
        template.setImageUrl("https://cdn.example.com/share.png");
        template.setLandingPageUrl("https://example.com/landing");
        Map<String, String> utmParams = new HashMap<>();
        utmParams.put("utm_source", "mosquito");
        utmParams.put("utm_medium", "share");
        template.setUtmParams(utmParams);

        service.registerTemplate("custom", template);

        Map<String, Object> meta = service.getShareMeta(101L, 202L, "custom");

        assertEquals("活动101", meta.get("title"));
        assertEquals("邀请用户202参与", meta.get("description"));
        assertEquals("https://cdn.example.com/share.png", meta.get("image"));

        String url = String.valueOf(meta.get("url"));
        assertTrue(url.contains("activityId=101"));
        assertTrue(url.contains("inviter=202"));
        assertTrue(url.contains("utm_source=mosquito"));
        assertTrue(url.contains("utm_medium=share"));
    }
}
