package svc

import (
	stdsql "database/sql"
	"juwan-backend/app/snowflake/rpc/snowflake"
	"juwan-backend/app/users/rpc/internal/config"
	"juwan-backend/app/users/rpc/internal/models"
	"juwan-backend/app/users/rpc/internal/utils"
	"juwan-backend/common/redisx"
	"juwan-backend/common/snowflakex"
	"juwan-backend/pkg/adapter"
	"time"

	"ariga.io/entcache"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	_ "github.com/jackc/pgx/v5/stdlib"
	"github.com/redis/go-redis/v9"
	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceContext struct {
	Config       config.Config
	UsersModelRW *models.Client
	UsersModelRO *models.Client
	RedisCluster *redis.ClusterClient
	Snowflake    snowflake.SnowflakeServiceClient
	JwtManager   *utils.JwtManager
}

func NewServiceContext(c config.Config) *ServiceContext {
	rawRW, err := stdsql.Open("pgx", c.DB.Master)
	if err != nil {
		panic(err)
	}
	rawRO, err := stdsql.Open("pgx", c.DB.Slave)
	if err != nil {
		panic(err)
	}
	RWConn := sql.OpenDB(dialect.Postgres, rawRW)
	ROConn := sql.OpenDB(dialect.Postgres, rawRO)

	logx.Infof("success to connect to postgres~")

	// Initialize Redis Cluster client from CacheConf
	redisConn, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second)
	if err != nil || redisConn == nil {
		logx.Errorf("redis connect master error: %s", err)
		panic(err)
	}
	redisCluster := redisConn.Client
	if redisCluster != nil {
		if redisConn.HasSlave {
			logx.Infof("success to connect to redis master/slave (M: %s, S: %s)", redisConn.MasterHost, redisConn.SlaveHost)
		} else {
			logx.Infof("success to connect to redis master (M: %s), slave not configured", redisConn.MasterHost)
		}
	}

	// Initialize JWT Manager
	jwtManager := utils.NewJwtManager(redisCluster, c.Jwt.SecretKey, c.Jwt.Issuer)

	RODrv := entcache.NewDriver(ROConn, entcache.TTL(time.Second*30), entcache.Levels(adapter.NewRedisCache(redisCluster)))
	RWDrv := entcache.NewDriver(RWConn, entcache.TTL(time.Second*30), entcache.Levels(adapter.NewRedisCache(redisCluster)))
	return &ServiceContext{
		Config:       c,
		UsersModelRW: models.NewClient(models.Driver(RWDrv)),
		UsersModelRO: models.NewClient(models.Driver(RODrv)),
		RedisCluster: redisCluster,
		JwtManager:   jwtManager,
		Snowflake:    snowflakex.NewClient(c.SnowflakeRpcConf),
	}
}
