package vpub

import (
	"crypto/aes"
	"database/sql"
	"encoding/hex"
	"fmt"
)

type Vpub struct {
	db  *sql.DB
	key []byte
}

func New(databaseURL string, key []byte) (Vpub, error) {
	db, err := sql.Open("postgres", databaseURL)
	return Vpub{db: db, key: key}, err
}

func EncryptAES(key []byte, plaintext string) string {
	c, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	out := make([]byte, len(plaintext))
	c.Encrypt(out, []byte(plaintext))
	return hex.EncodeToString(out)
}

func (v Vpub) FindOrCreateKey(name string) string {
	padded := fmt.Sprintf("%16s", name)
	key := EncryptAES(v.key, padded)[0:20]

	query := `
        insert into keys (key) values ($1) ON CONFLICT do nothing
    `

	_, err := v.db.Exec(query, key[:20])
	if err != nil {
		fmt.Println(err)
	}

	return key
}
