package svc

import (
	"sundynix-micro-go/app/auth/api/internal/config"
	"sundynix-micro-go/app/plant/rpc/plantservice"
	"sundynix-micro-go/app/system/rpc/systemservice"
	"sundynix-micro-go/common/utils/captcha"

	"github.com/redis/go-redis/v9"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config    config.Config
	SystemRpc systemservice.SystemService
	// 各业务 RPC（可选，新增小程序时在此追加）
	PlantRpc plantservice.PlantService
	// RadioRpc radioservice.RadioService
}

func NewServiceContext(c config.Config) *ServiceContext {
	// 初始化 Redis 并注入验证码存储
	rdb := redis.NewClient(&redis.Options{
		Addr:     c.Redis.Host,
		Password: c.Redis.Pass,
		DB:       c.Redis.DB,
	})
	captcha.InitWithRedis(rdb)
	logx.Infof("验证码存储已切换至 Redis (DB%d)", c.Redis.DB)

	svc := &ServiceContext{
		Config:    c,
		SystemRpc: systemservice.NewSystemService(zrpc.MustNewClient(c.SystemRpc)),
	}

	// 可选: PlantRpc（配置了才连接，避免强依赖）
	if c.PlantRpc.Etcd.Key != "" || len(c.PlantRpc.Endpoints) > 0 {
		svc.PlantRpc = plantservice.NewPlantService(zrpc.MustNewClient(c.PlantRpc))
		logx.Info("PlantRpc 已连接")
	}

	return svc
}
