package com.mosquito.project.service;

import com.mosquito.project.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

@Service
public class ShareConfigService {

    private static final Logger log = LoggerFactory.getLogger(ShareConfigService.class);

    private final AppConfig appConfig;
    private final Map<String, ShareTemplate> templates = new HashMap<>();

    public static class ShareTemplate {
        private String title;
        private String description;
        private String imageUrl;
        private String landingPageUrl;
        private Map<String, String> utmParams = new HashMap<>();

        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public String getImageUrl() { return imageUrl; }
        public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
        public String getLandingPageUrl() { return landingPageUrl; }
        public void setLandingPageUrl(String landingPageUrl) { this.landingPageUrl = landingPageUrl; }
        public Map<String, String> getUtmParams() { return utmParams; }
        public void setUtmParams(Map<String, String> utmParams) { this.utmParams = utmParams; }
    }

    public ShareConfigService(AppConfig appConfig) {
        this.appConfig = appConfig;
    }

    public void registerTemplate(String name, ShareTemplate template) {
        templates.put(name, template);
        log.info("Registered share template: {}", name);
    }

    public ShareTemplate getTemplate(String name) {
        return templates.get(name);
    }

    public String buildShareUrl(Long activityId, Long userId, String templateName, Map<String, String> extraParams) {
        ShareTemplate template = templates.get(templateName);
        if (template == null) {
            template = getDefaultTemplate(activityId);
        }

        StringBuilder url = new StringBuilder(template.getLandingPageUrl());
        url.append("?activityId=").append(activityId);
        url.append("&inviter=").append(userId);

        if (template.getUtmParams() != null) {
            template.getUtmParams().forEach((k, v) -> url.append("&").append(k).append("=").append(v));
        }

        if (extraParams != null) {
            extraParams.forEach((k, v) -> {
                if (k != null && v != null) {
                    url.append("&").append(k).append("=").append(java.net.URLEncoder.encode(v, java.nio.charset.StandardCharsets.UTF_8));
                }
            });
        }

        return url.toString();
    }

    public Map<String, Object> getShareMeta(Long activityId, Long userId, String templateName) {
        ShareTemplate template = templates.get(templateName);
        if (template == null) {
            template = getDefaultTemplate(activityId);
        }

        Map<String, Object> meta = new HashMap<>();
        meta.put("title", resolvePlaceholders(template.getTitle(), activityId, userId));
        meta.put("description", resolvePlaceholders(template.getDescription(), activityId, userId));
        meta.put("image", resolvePlaceholders(template.getImageUrl(), activityId, userId));
        meta.put("url", buildShareUrl(activityId, userId, templateName, null));
        return meta;
    }

    private ShareTemplate getDefaultTemplate(Long activityId) {
        ShareTemplate defaultTemplate = new ShareTemplate();
        defaultTemplate.setTitle("邀请您参与活动");
        defaultTemplate.setDescription("快来加入我们的活动吧！");
        defaultTemplate.setImageUrl(appConfig.getShortLink().getCdnBaseUrl() + "/default-share.png");
        defaultTemplate.setLandingPageUrl(appConfig.getShortLink().getLandingBaseUrl());
        return defaultTemplate;
    }

    private String resolvePlaceholders(String text, Long activityId, Long userId) {
        if (text == null) return "";
        return text.replace("{{activityId}}", String.valueOf(activityId))
                   .replace("{{userId}}", String.valueOf(userId))
                   .replace("{{timestamp}}", String.valueOf(System.currentTimeMillis()));
    }
}
