package Database

import (
	"errors"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

func GetUserById(id string) (Models.User, error) {
	var (
		user Models.User
		err  error
	)

	err = DB.Preload(clause.Associations).
		First(&user, "id = ?", id).
		Error

	return user, err
}

func GetUserByUsername(username string) (Models.User, error) {
	var (
		user Models.User
		err  error
	)

	err = DB.Preload(clause.Associations).
		First(&user, "username = ?", username).
		Error

	return user, err
}

func CheckUniqueUsername(username string) error {
	var (
		exists bool
		err    error
	)

	err = DB.Model(Models.User{}).
		Select("count(*) > 0").
		Where("username = ?", username).
		Find(&exists).
		Error

	if err != nil {
		return err
	}

	if exists {
		return errors.New("Invalid username")
	}

	return nil
}

func CreateUser(user *Models.User) error {
	var err error

	err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
		Create(user).
		Error

	return err
}

func UpdateUser(id string, user *Models.User) error {
	var err error
	err = DB.Model(&user).
		Omit("id").
		Where("id = ?", id).
		Updates(user).
		Error

	if err != nil {
		return err
	}

	err = DB.Model(Models.User{}).
		Where("id = ?", id).
		First(user).
		Error

	return err
}

func DeleteUser(user *Models.User) error {
	return DB.Session(&gorm.Session{FullSaveAssociations: true}).
		Delete(user).
		Error
}
