package com.ruoyi.app.utils.linepay;

import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/** LINE Pay v4 HMAC-SHA256 signature calculator. */
@Component
public class LinePaySigner {

    public String sign(String channelSecret, String uri, String bodyOrQuery, String nonce) {
        require(channelSecret, "channelSecret");
        require(uri, "uri");
        require(nonce, "nonce");
        String payload = channelSecret + uri + (bodyOrQuery == null ? "" : bodyOrQuery) + nonce;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(channelSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] digest = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(digest);
        } catch (Exception e) {
            throw new IllegalStateException("Unable to sign LINE Pay request", e);
        }
    }

    private static void require(String value, String name) {
        if (value == null || value.isEmpty()) {
            throw new IllegalArgumentException(name + " is required");
        }
    }
}

