package models

import (
	"crypto/rand"

	"gorm.io/gorm"
	"spahl.ddns.net/jasper/wok-able-backend/auth"
)

const saltSize = 64

type User struct {
	ID           uint       `json:"-" gorm:"primary key"`
	Username     string     `json:"username" gorm:"unique;not null"`
	Email        string     `json:"email" gorm:"unique;not null"`
	Password     string     `json:"password" gorm:"-" binding:"required"`
	PasswordHash []byte     `json:"-" gorm:"not null"`
	Salt         []byte     `json:"-" gorm:"not null"`
	CardDecks    []CardDeck `json:"-"`
	Cards        []Card     `json:"-"`
}
type Auth struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
	salt := make([]byte, saltSize)
	if _, err = rand.Read(salt[:]); err != nil {
		return
	}
	u.Salt = salt
	u.PasswordHash, err = auth.HashPassword(u.Password, u.Salt)
	return
}
