package models

import (
	"bsm/full/module/base/passport/internal/impl"
	"bsm/full/module/base/passport/internal/vars"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func InitData() error {
	var cnt int64
	var err error
	err = impl.DBService.Model(&PassportAccount{}).Where("account=?", "demo").Count(&cnt).Error
	if err != nil {
		return err
	}
	if cnt == 0 {
		salt := utils.ULID()
		hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("welcome"+salt), bcrypt.MinCost)
		pa := PassportAccount{
			Std_IICUDS: types.Std_IICUDS{
				Identity: utils.UUID(),
				Status:   vars.Status_Normal,
			},
			Account:  "demo",
			Phone:    "",
			Password: string(hashedPassword),
			Salt:     salt,
		}
		err = impl.DBService.Create(&pa).Error
		if err != nil {
			return err
		}
	}

	return nil
}

func PassportAccountExists(key, val string) bool {
	var count int64
	err := impl.DBService.Model(&PassportAccount{}).Where(key+" = ?", val).Count(&count).Error
	if err != nil {
		return false
	}
	return count > 0
}

func CreateAccount(pa *PassportAccount, nickname string) (err error) {
	return impl.DBService.Transaction(func(tx *gorm.DB) error {

		// 插入扩展表
		pe := new(PassportData)
		pe.PassportID = pa.ID
		pe.PassportIdentity = pa.Identity
		pe.Nickname = nickname

		if err := tx.Create(pe).Error; err != nil {
			return err
		}

		return nil
	})
}
