package logic

import (
	"context"
	"errors"

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

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

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

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

func (l *GetUserByOpenIdLogic) GetUserByOpenId(in *system.GetUserByOpenIdReq) (*system.GetUserByOpenIdResp, error) {
	var u sysModel.SundynixUser
	if err := l.svcCtx.DB.Where("open_id = ?", in.OpenId).First(&u).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, status.Error(codes.NotFound, "用户不存在")
		}
		return nil, status.Error(codes.Internal, "查询失败")
	}
	return &system.GetUserByOpenIdResp{User: convertUserToProto(&u)}, nil
}
