package repository

import (
	"errors"
	"gorm.io/gorm"
	"wireguard-dashboard/client"
	"wireguard-dashboard/constant"
	"wireguard-dashboard/http/param"
	"wireguard-dashboard/model/entity"
	"wireguard-dashboard/model/vo"
	"wireguard-dashboard/utils"
)

type user struct {
	*gorm.DB
}

func User() user {
	return user{
		client.DB,
	}
}

// List
// @description: 用户列表
// @receiver r
// @param p
// @return data
// @return total
// @return err
func (r user) List(p param.UserList) (data []vo.User, total int64, err error) {
	err = r.Model(&entity.User{}).Scopes(utils.Page(p.Current, p.Size)).
		Select("id", "created_at", "updated_at", "avatar", "email", "name", "account", "is_admin", "status").Order("created_at DESC").
		Find(&data).Offset(-1).Limit(-1).Count(&total).Error

	return
}

// GetUserById
// @description: 根据id获取用户信息
// @receiver r
// @param id
// @return *entity.User
// @return error
func (r user) GetUserById(id string) (data *entity.User, err error) {
	err = r.Where("id = ?", id).First(&data).Error
	return
}

// GetUserByAccount
// @description: 通过账户号获取用户信息
// @receiver r
// @param account
// @return data
// @return err
func (r user) GetUserByAccount(account string) (data *entity.User, err error) {
	err = r.Where("account = ?", account).First(&data).Error
	return
}

// Save
// @description: 创建/更新用户
// @receiver r
// @param ent
// @return err
func (r user) Save(ent *entity.User) (err error) {
	// 更新
	if ent.Id != "" {
		updates := map[string]any{
			"name":     ent.Name,
			"avatar":   ent.Avatar,
			"email":    ent.Email,
			"is_admin": ent.IsAdmin,
			"status":   ent.Status,
		}

		return r.Model(&entity.User{}).Where("id = ?", ent.Id).Updates(&updates).Error
	}

	defaultPassword := utils.Password().GenerateHashPassword("admin123")
	if ent.Password == "" { // 没有密码给一个默认密码
		ent.Password = defaultPassword
	} else {
		ent.Password = utils.Password().GenerateHashPassword(ent.Password)
	}

	// 没有头像就生成一个头像
	if ent.Avatar == "" {
		ent.Avatar, _ = utils.Avatar().GenerateAvatar()
	}

	// 创建
	return r.Create(&ent).Error
}

// ChangePassword
// @description: 变更密码
// @receiver r
// @param p
// @param userId
// @return err
func (r user) ChangePassword(p param.ChangePassword, userId string) (err error) {
	password := utils.Password().GenerateHashPassword(p.NewPassword)
	return r.Model(&entity.User{}).Where("id = ?", userId).Update("password", password).Error
}

// ChangeUserState
// @description: 变更用户状态
// @receiver r
// @param p
// @return err
func (r user) ChangeUserState(p param.ChangeUserState) (err error) {
	return r.Model(&entity.User{}).Where("id = ?", p.ID).Update("status", p.Status).Error
}

// DeleteUser
// @description: 删除管理员
// @receiver r
// @param id
// @return err
func (r user) DeleteUser(loginUser *entity.User, id string) (err error) {
	// 不能删除自身以及超级管理员，超级管理员只有 名为admin的管理员可以删除
	userInfo, err := r.GetUserById(id)
	if err != nil {
		return
	}

	if userInfo.Id == loginUser.Id {
		return errors.New("不可删除自己")
	}

	if userInfo.IsAdmin == constant.SuperAdmin && loginUser.Account != "admin" {
		return errors.New("非无敌管理员不可清空超管")
	}

	if userInfo.Account == "admin" {
		return errors.New("不可删除宇宙第一无敌管理员，删了你就G了！")
	}

	// 可删除
	return r.Model(&entity.User{}).Where("id = ?", id).Delete(userInfo).Error
}
