package security

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"os"
	"path/filepath"
)

func generatePrivateKey(keysPath string, keyName string) error {

	// Generate a new private key.
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return fmt.Errorf("generate-private-key: unable to generate key: %w", err)
	}

	fileName := fmt.Sprintf("%s.pem", keyName)
	keyName = filepath.Join(keysPath, fileName)

	// Create a file for the private key information in PEM form.
	privateFile, err := os.Create(keyName)
	if err != nil {
		return fmt.Errorf("creating private file: %w", err)
	}
	defer privateFile.Close()

	// Construct a PEM block for the private key.
	privateBlock := pem.Block{
		Type:  "PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
	}

	// Write the private key to the private key file.
	if err := pem.Encode(privateFile, &privateBlock); err != nil {
		return fmt.Errorf("generate-private-key: unable to encode: %w", err)
	}

	return nil
}
