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 GetClientByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

// 获取客户端信息
func (l *GetClientByIdLogic) GetClientById(in *system.GetClientByIdReq) (*system.GetClientByIdResp, error) {
	var client sysModel.SundynixClient
	err := l.svcCtx.DB.Where("client_id = ?", in.ClientId).First(&client).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			l.Infof("[GetClientById] 客户端不存在 | clientId=%s", in.ClientId)
			return nil, status.Error(codes.NotFound, "客户端不存在")
		}
		l.Errorf("[GetClientById] ❌ 查询客户端失败 | clientId=%s | err=%v", in.ClientId, err)
		return nil, status.Error(codes.Internal, "查询客户端失败")
	}

	return &system.GetClientByIdResp{
		Client: &system.ClientInfo{
			Id:             client.ID,
			ClientId:       client.ClientID,
			Name:           client.Name,
			GrantType:      client.GrantType,
			AdditionalInfo: client.AdditionalInfo,
			ActiveTimeout:  client.ActiveTimeout,
		},
	}, nil
}
