/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package auxx509

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"time"
)

func CreateSelfSignedCert(subject string, dnsNames ...string) ([]byte, []byte, error) {
	var err error
	certPem := make([]byte, 0)
	keyPem := make([]byte, 0)

	now := time.Now()

	const yearsAfter int = 10
	const keySize int = 2048

	key, err := rsa.GenerateKey(rand.Reader, keySize)
	if err != nil {
		err := fmt.Errorf("Can't create a private key: %v", err)
		return certPem, keyPem, err

	}
	keyPemBlock := pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	}
	keyPem = pem.EncodeToMemory(&keyPemBlock)

	names := make([]string, 0)
	names = append(names, subject)
	names = append(names, dnsNames...)
	tml := x509.Certificate{
		SerialNumber: big.NewInt(now.Unix()),
		NotBefore:    now,
		NotAfter:     now.AddDate(yearsAfter, 0, 0),
		Subject: pkix.Name{
			CommonName: subject,
		},
		DNSNames:              names,
		BasicConstraintsValid: true,
	}
	certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
	if err != nil {
		return certPem, keyPem, fmt.Errorf("Can't create a certificate: %v", err)

	}
	certPemBlock := pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	}
	certPem = pem.EncodeToMemory(&certPemBlock)
	if err != nil {
		return certPem, keyPem, err
	}
	return certPem, keyPem, err
}
