package aux509

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

func GetTLSCert(orgName, commonName string) (tls.Certificate, error) {
	var err error
	var res tls.Certificate
	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: %w", err)
		return res, err

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

	tml := x509.Certificate{
		SerialNumber: big.NewInt(now.Unix()),
		NotBefore:    now,
		NotAfter:     now.AddDate(yearsAfter, 0, 0),
		Subject: pkix.Name{
			CommonName:   commonName,
			Organization: []string{orgName},
		},
		BasicConstraintsValid: true,
	}
	certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
	if err != nil {
		return res, fmt.Errorf("Can't create a certificate: %w", err)

	}
	certPemBlock := pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	}
	certPem := string(pem.EncodeToMemory(&certPemBlock))
	if err != nil {
		return res, err
	}
	tlsCert, err := tls.X509KeyPair([]byte(certPem), []byte(keyPem))
	if err != nil {
		return res, err
	}
	res = tlsCert
	return res, err
}
