// genkey generates an ES256 JWK keypair for OAuth client authentication
package main

import (
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"

	"github.com/haileyok/atproto-oauth-golang/helpers"
)

func main() {
	fmt.Println("Generating OAuth configuration...")
	fmt.Println()

	// Generate cookie secret
	cookieSecret := make([]byte, 32)
	if _, err := rand.Read(cookieSecret); err != nil {
		fmt.Fprintf(os.Stderr, "Error generating cookie secret: %v\n", err)
		os.Exit(1)
	}

	// Generate ES256 JWK
	key, err := helpers.GenerateKey(nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error generating JWK: %v\n", err)
		os.Exit(1)
	}

	// Marshal JWK to JSON
	keyJSON, err := json.Marshal(key)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error marshaling JWK: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("Add these values to your oauth.env file:")
	fmt.Println()
	fmt.Printf("OAUTH_COOKIE_SECRET=%s\n", hex.EncodeToString(cookieSecret))
	fmt.Printf("OAUTH_PRIVATE_JWK=%s\n", string(keyJSON))
	fmt.Println()
	fmt.Println("Keep these values secret!")
}
