/**
 * @Author: ZhaoYadong
 * @Date: 2024-02-27 21:09:45
 * @LastEditors: ZhaoYadong
 * @LastEditTime: 2024-02-28 09:13:35
 * @FilePath: /server/Users/edy/go/src/passport/internal/models/passport_account.go
 */
// Models generated by mesh dev cli,@Author: David Yan(david.yan@qq.com).
package models

import (
	"errors"

	"bsm/full/module/base/passport/internal/impl"
	"bsm/full/module/base/passport/internal/vars"
	"git.apinb.com/bsm-sdk/core/database"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/types"
	"gorm.io/gorm"
)

/*
 * PassportAccount
 * Comment: 通行证帐号表
 * Version: 10
 * Created: 2022-04-12 10:44:51 , Updated:0001-01-01 00:00:00
 */
type PassportAccount struct {
	types.Std_IICUDS
	Account  string `gorm:"column:account;type:varchar(255);default:'';" json:"account"` // 帐号
	Phone    string `gorm:"column:phone;type:varchar(20);default:'';" json:"phone"`      // 手机号
	Email    string `gorm:"column:email;type:varchar(255);default:'';" json:"email"`     // Email
	Password string `gorm:"column:password;type:varchar(255);not null;" json:"password"` // 密码
	Salt     string `gorm:"column:salt;type:varchar(255);not null;" json:"salt"`         // 密码盐
}

func init() {
	database.AppendMigrate(&PassportAccount{})
}

// TableName .
func (table *PassportAccount) TableName() string {
	return "passport_account" //对应数据库表名
}

// GetPassportAccountByField 根据特定字段值获取PassportAccount对象
func GetPassportAccountByField(field string, value any) (*PassportAccount, error) {
	var (
		data      PassportAccount
		condition = map[string]any{field: value}
	)
	err := impl.DBService.Where(condition).First(&data).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errcode.ErrNotFound(404, "Account not found")
		}
		return nil, errcode.ErrDB
	}

	if data.Status == vars.Status_Disable {
		return nil, errcode.ErrPermissionDenied
	}

	return &data, nil
}
