package users

import (
	"database/sql"
	"maxwarden/query"
)

type User struct {
	ID             int32  `db:"id"`
	Username       string `db:"username"`
	Email          string `db:"email"`
	Firstname      string `db:"firstname"`
	Lastname       string `db:"lastname"`
	Password       string `db:"password"`
	FailedAttempts int32  `db:"failed_attempts"`
	SecurityStamp  string `db:"security_stamp"`
	LastLogin      string `db:"last_login"`
	Data           []byte `db:"data"`
}

func FetchById(id int32) (User, error) {
	qb := &query.QueryBuilder{}
	qb.BaseSQL = "SELECT * FROM users u WHERE u.id = ?"

	return query.Get[User](qb, query.DB, id)
}

func FetchByUsername(username string) (User, error) {
	qb := &query.QueryBuilder{}
	qb.BaseSQL = "SELECT * FROM users u WHERE u.username = ?"

	return query.Get[User](qb, query.DB, username)
}

func FetchSecurityStamp(userid int) (string, error) {
	qb := &query.QueryBuilder{}
	qb.BaseSQL = "SELECT u.security_stamp FROM users u WHERE u.id = ?"

	return query.Get[string](qb, query.DB, userid)
}

func Update(user User) (sql.Result, error) {
	qb := &query.QueryBuilder{}
	qb.BaseSQL = "UPDATE users"

	qb.Setters = []query.QuerySetter{
		{Column: "failed_attempts", Parameter: user.FailedAttempts},
		{Column: "data", Parameter: user.Data},
	}

	qb.Where = []query.QueryFilter{
		{Column: "id", Operator: query.EQ, Parameter: user.ID},
	}

	return query.Update[User](qb, query.DB)
}
