package server

import (
	"common/db/redis"
	"common/net/http/http_resp"
	"common/proto/ss/grpc_pb"
	"common/utils"
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"user/internal/dao/model"
	"user/internal/dao/repository"
)

func (s *Server) Login(ctx context.Context, req *grpc_pb.LoginReq) (*grpc_pb.LoginResp, error) {
	userDao := repository.NewUserDao(ctx, redis.GetCacheClient())
	user, err := userDao.FindByPhone(req.Phone)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			user = &model.User{
				Phone: req.Phone,
			}
			if err := userDao.Create(user); err != nil {
				return nil, err
			}
			user.Name = fmt.Sprintf("user_%d", user.Sn)
			_ = userDao.Updates(user)
		} else {
			return nil, err
		}
	}

	return &grpc_pb.LoginResp{
		USN:  user.Sn,
		Name: user.Name,
	}, nil
}

func (s *Server) GetUserInfo(ctx context.Context, req *grpc_pb.GetUserInfoReq) (*grpc_pb.GetUserInfoResp, error) {
	if !utils.ShouldBindUsn(ctx, &req.USN) {
		return nil, http_resp.ParamError
	}
	userDao := repository.NewUserDao(ctx, redis.GetCacheClient())
	user, err := userDao.FindBySn(req.USN)
	if err != nil {
		return nil, err
	}

	return &grpc_pb.GetUserInfoResp{
		USN:  user.Sn,
		Name: user.Name,
	}, nil
}
