package agency

import (
	"context"
	"errors"
	"time"

	"bsm/full/module/ec/market/internal/impl"
	"bsm/full/module/ec/market/internal/models"
	"bsm/full/module/ec/market/internal/password"
	pb "bsm/full/module/ec/market/pb"

	"git.apinb.com/bsm-sdk/core/crypto/encipher"
	"git.apinb.com/bsm-sdk/core/errcode"
	"gorm.io/gorm"
)

// 登录
func Login(ctx context.Context, in *pb.LoginRequest) (reply *pb.LoginReply, err error) {
	var marketData models.MarketAgency

	if in.Account == "" || in.Password == "" {
		return nil, errcode.ErrInvalidArgument
	}

	err = impl.DBService.Where("account=? and id<>0", in.Account).First(&marketData).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errcode.ErrAccountNotFound
		}
		return nil, errcode.ErrDB
	}
	// 密码校验
	if !password.Verify(marketData.Password, in.Password) {
		return nil, errcode.ErrPassword
	}

	// 账号状态校验
	if marketData.Status == models.DisabledStatus {
		return nil, errcode.ErrAccountDisabled
	}

	// 认证状态校验
	if marketData.Approve != 2 {
		return nil, errcode.ErrDisabled
	}

	market := models.Std_Market{
		Market_ID:       marketData.ID,
		Market_Identity: marketData.Identity,
	}

	token, err := encipher.GenerateTokenAes(marketData.ID, marketData.Identity, "", "", market, map[string]string{})
	if err != nil {
		return nil, err
	}

	// 更新登录时间
	marketData.LastLoginAt = time.Now()
	err = impl.DBService.Debug().Where("id = ?", marketData.ID).Select("last_login_at").Updates(marketData).Error
	if err != nil {
		return nil, err
	}

	return &pb.LoginReply{
		Token:          token,
		Identity:       marketData.Identity,
		Name:           marketData.Name,
		Account:        marketData.Account,
		MarketName:     marketData.OrgName,
		MarketIdentity: marketData.Identity,
		Status:         int32(marketData.Status),
		CreatedAt:      marketData.CreatedAt.Format(time.DateTime),
	}, nil

}
