package com.kingdee.eas.custom.integration.base.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * state 编解码工具，在 OAuth 全流程中携带 redirect 和 appType。
 *
 * <p>格式：{@code Base64Url(redirect + "|" + appType)}</p>
 *
 * <p>用法：</p>
 * <ul>
 *   <li>{@link #generate(String, String)} — sHR 生成待办链接时调用</li>
 *   <li>{@link #extractRedirect(String)} — 从 state 中提取重定向地址</li>
 *   <li>{@link #extractAppType(String)} — 从 state 中提取应用类型</li>
 * </ul>
 */
@Service
public class StateValidator {

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

    private static final String DELIMITER = "|";

    public String generate(String redirect, String appType) {
        String raw = redirect + DELIMITER + appType;
        return Base64.getUrlEncoder().withoutPadding()
                .encodeToString(raw.getBytes(StandardCharsets.UTF_8));
    }

    public String extractRedirect(String state) {
        try {
            String raw = decode(state);
            if (raw == null) return null;
            int lastPipe = raw.lastIndexOf(DELIMITER);
            return lastPipe < 0 ? raw : raw.substring(0, lastPipe);
        } catch (Exception e) {
            log.warn("state decode failed: {}", e.getMessage());
            return null;
        }
    }

    public String extractAppType(String state) {
        try {
            String raw = decode(state);
            if (raw == null) return null;
            int lastPipe = raw.lastIndexOf(DELIMITER);
            return lastPipe < 0 ? null : raw.substring(lastPipe + 1);
        } catch (Exception e) {
            log.warn("state decode failed: {}", e.getMessage());
            return null;
        }
    }

    private String decode(String state) {
        if (state == null || state.trim().isEmpty()) return null;
        return new String(
                Base64.getUrlDecoder().decode(state), StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        String base = "aHR0cDovL2Voci5zaGljaHVhbmd5aS5jbjo4MDgwL3Noci9keW5hbWljLmRvP2luRnJhbWU9dHJ1ZSZmcm9tSGVhZGVyPXRydWUmdWlwaz1jb20ua2luZ2RlZS5zaHIucGVyZndlYi5hcHAucGVyZnBvcnRhbC5jb3JlJnNlcnZpY2VJZD1mVWpTcVFLMVJvdVphRUpVSTJqSDV2STlLUkElM0R8ZXNz";
        StateValidator stateValidator = new StateValidator();
        String s = stateValidator.extractRedirect(base);
        System.out.println(s);
    }

}
