package repositories

import (
	"gorm.io/gorm"

	"git.dynamicdiscord.de/kalipso/zineshop/models"
)

type UserRepository interface {
	Create(models.User) (models.User, error)
	GetByEmail(string) (models.User, error)
	GetById(interface{}) (models.User, error)
	IsEmpty() (bool, error)
}

type GORMUserRepository struct {
	DB *gorm.DB
}

func NewGORMUserRepository(db *gorm.DB) UserRepository {
	return &GORMUserRepository{
		DB: db,
	}
}

func (u *GORMUserRepository) Create(user models.User) (models.User, error) {
	result := u.DB.Create(&user)

	if result.Error != nil {
		return models.User{}, result.Error
	}

	return user, nil
}

func (u *GORMUserRepository) GetByEmail(email string) (models.User, error) {
	var user models.User
	result := u.DB.First(&user, "email = ?", email)

	if result.Error != nil {
		return models.User{}, result.Error
	}

	return user, nil
}

func (u *GORMUserRepository) GetById(id interface{}) (models.User, error) {
	var user models.User
	result := u.DB.First(&user, id)

	if result.Error != nil {
		return models.User{}, result.Error
	}

	return user, nil
}

func (u *GORMUserRepository) IsEmpty() (bool, error) {
	var user models.User
	result := u.DB.First(&user)

	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return true, nil
		} else {
			return false, result.Error
		}
	}

	return false, nil
}
