package svc

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

	"entgo.io/ent/dialect"
	_ "github.com/jackc/pgx/v5/stdlib"
	"github.com/zeromicro/go-zero/zrpc"

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

type ServiceContext struct {
	Config          config.Config
	UserVeriModelRW *models.UserVerificationsClient
	UserVeriModelRO *models.UserVerificationsClient
	RedisClient     *redis.ClusterClient
	SnowflakeRpc    snowflake.SnowflakeServiceClient
	UserRpc         usercenter.Usercenter
}

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~")

	redisConn, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second)
	if err != nil || redisConn == nil {
		logx.Errorf("redis connect master error: %s", err)
		panic(err)
	}

	RWDrv := entcache.NewDriver(RWConn, entcache.TTL(time.Second*30), entcache.Levels(adapter.NewRedisCache(redisConn.Client)))
	RODrv := entcache.NewDriver(ROConn, entcache.TTL(time.Second*30), entcache.Levels(adapter.NewRedisCache(redisConn.Client)))
	return &ServiceContext{
		Config:          c,
		UserVeriModelRW: models.NewClient(models.Driver(RWDrv)).UserVerifications,
		UserVeriModelRO: models.NewClient(models.Driver(RODrv)).UserVerifications,
		RedisClient:     redisConn.Client,
		SnowflakeRpc:    snowflakex.NewClient(c.SnowflakeRpcConf),
		UserRpc:         usercenter.NewUsercenter(zrpc.MustNewClient(c.UserRpcConf)),
	}
}
