package pki

import (
	"crypto"
	"crypto/sha512"
	"encoding/hex"
	"time"

	"git.paulbsd.com/paulbsd/pki/src/config"
	"github.com/go-acme/lego/v4/registration"
)

// CreateInitialUser creates initial user with password
func (u *User) CreateInitialUser(cfg *config.Config) (err error) {
	*u = User{Username: cfg.Init.Username}

	has, err := cfg.Db.Get(u)

	if !has {
		hashedPassword := sha512.Sum512([]byte(cfg.Init.Password))
		base64Password := hex.EncodeToString(hashedPassword[:])

		*u = User{
			Username:       cfg.Init.Username,
			PasswordSHA512: base64Password,
			Email:          cfg.Init.Email}
		cfg.Db.Insert(u)
	}
	return
}

// User describe accounts
type User struct {
	ID             int                    `xorm:"pk autoincr"`
	Username       string                 `xorm:"text notnull unique"`
	PasswordSHA512 string                 `xorm:"text notnull"`
	Email          string                 `xorm:"text"`
	PrivateKey     string                 `xorm:"text"`
	Created        time.Time              `xorm:"created notnull"`
	Updated        time.Time              `xorm:"updated notnull"`
	Registration   *registration.Resource `xorm:"-"`
	key            crypto.PrivateKey      `xorm:"-"`
}
