package logic

import (
	"context"
	"errors"
	"time"

	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"
	"sundynix-micro-go/common/utils/hash"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
)

type LoginByAccountLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginByAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginByAccountLogic {
	return &LoginByAccountLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *LoginByAccountLogic) LoginByAccount(in *system.LoginByAccountReq) (*system.LoginByAccountResp, error) {
	var u sysModel.SundynixUser
	err := l.svcCtx.DB.Where("account = ?", in.Account).First(&u).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, status.Error(codes.NotFound, "账号不存在")
		}
		return nil, status.Error(codes.Internal, "查询用户失败")
	}
	if !hash.BcryptCheck(in.Password, u.Password) {
		return nil, status.Error(codes.Unauthenticated, "密码错误")
	}

	// 更新最后登录时间
	now := time.Now()
	l.svcCtx.DB.Model(&u).Update("last_login_at", now)
	u.LastLoginAt = &now

	return &system.LoginByAccountResp{User: convertUserToProto(&u)}, nil
}
