package main

import (
	"context"
	"log"
	"time"

	pb "bsm/full/module/base/passport/pb"
	"git.apinb.com/bsm-sdk/core/utils"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
)

const (
	address = "api.apinb.com:10020" // 本地测试地址
)

func main() {
	log.Println("开始测试 Initial Service...")

	// 测试健康检查
	testHello()

	log.Println("所有测试完成!")
}

// 创建gRPC连接
func createConnection() (*grpc.ClientConn, error) {
	// 使用不安全连接进行本地测试
	conn, err := grpc.Dial(address,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithBlock(),
	)
	return conn, err
}

// 创建上下文和元数据
func createContext() (context.Context, context.CancelFunc) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

	newMetaData := metadata.New(nil)
	newMetaData.Set("request_id", utils.UUID())
	newMetaData.Set("workspace", "def")
	newMetaData.Set("authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NywiaWRlbnRpdHkiOiIwMTk5M2RmMy0yMjk4LTdlZGYtOTIwMS1mYmNhNmI5NDg3NzMiLCJleHRlbmQiOnsicmlnaHRzIjoiIn0sImNsaWVudCI6IiIsIm93bmVyIjpudWxsLCJyb2xlIjoiIiwiZXhwIjoxNzYwNDEzODE0LCJuYmYiOjE3NjAzMjc0MTQsImlhdCI6MTc2MDMyNzQxNH0.3e5O76M6NRxqL8CDQyojA6Qom0dsJWrNPX2PcP8VPig")
	outCtx := metadata.NewOutgoingContext(ctx, newMetaData)

	return outCtx, cancel
}

// 测试健康检查
func testHello() {
	log.Println("测试健康检查...")

	conn, err := createConnection()
	if err != nil {
		log.Printf("连接失败: %v", err)
		return
	}
	defer conn.Close()

	client := pb.NewVerifyClient(conn)
	ctx, cancel := createContext()
	defer cancel()

	resp, err := client.Request(ctx, &pb.VerifyRequest{Provider: "local"})
	if err != nil {
		log.Printf("调用失败: %v", err)
		return
	}
	log.Printf("Hello 响应: %v", resp)
}
