package com.swoosh.microblog.data.api

import io.jsonwebtoken.Jwts
import java.util.Date
import javax.crypto.spec.SecretKeySpec

object GhostJwtGenerator {

    /**
     * Generate a Ghost Admin API JWT from the admin API key.
     * The key format is: {key_id}:{secret_hex}
     * We sign an HS256 JWT with 5-minute expiry.
     */
    fun generateToken(adminApiKey: String): String {
        val parts = adminApiKey.split(":")
        require(parts.size == 2) { "Invalid API key format. Expected {id}:{secret}" }

        val keyId = parts[0]
        val secretHex = parts[1]

        // Decode hex secret to bytes
        val secretBytes = secretHex.chunked(2)
            .map { it.toInt(16).toByte() }
            .toByteArray()

        val now = Date()
        val expiry = Date(now.time + 5 * 60 * 1000) // 5 minutes

        val key = SecretKeySpec(secretBytes, "HmacSHA256")

        return Jwts.builder()
            .header()
            .add("kid", keyId)
            .and()
            .issuedAt(now)
            .expiration(expiry)
            .audience().add("/admin/")
            .and()
            .signWith(key)
            .compact()
    }
}
