package db

import (
	cortypes "gitlink.org.cn/cloudream/jcs-pub/coordinator/types"
	"gorm.io/gorm"
)

type UserDB struct {
	*DB
}

func (db *DB) User() *UserDB {
	return &UserDB{DB: db}
}

func (db *UserDB) GetByID(ctx SQLContext, userID cortypes.UserID) (cortypes.User, error) {
	var ret cortypes.User
	err := ctx.Table("User").Where("UserID = ?", userID).First(&ret).Error
	return ret, err
}

func (db *UserDB) GetByName(ctx SQLContext, name string) (cortypes.User, error) {
	var ret cortypes.User
	err := ctx.Table("User").Where("Name = ?", name).First(&ret).Error
	return ret, err
}

func (db *UserDB) Create(ctx SQLContext, name string) (cortypes.User, error) {
	_, err := db.GetByName(ctx, name)
	if err == nil {
		return cortypes.User{}, gorm.ErrDuplicatedKey
	}
	if err != gorm.ErrRecordNotFound {
		return cortypes.User{}, err
	}

	user := cortypes.User{Name: name}
	err = ctx.Table("User").Create(&user).Error
	return user, err
}

func (*UserDB) Delete(ctx SQLContext, userID cortypes.UserID) error {
	return ctx.Table("User").Delete(&cortypes.User{UserID: userID}).Error
}
