package svc

import (
	stdsql "database/sql"
	"juwan-backend/app/review/rpc/internal/config"
	"juwan-backend/app/review/rpc/internal/models"
	"juwan-backend/app/snowflake/rpc/snowflake"
	"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"
)

type ServiceContext struct {
	Config        config.Config
	Snowflake     snowflake.SnowflakeServiceClient
	ReviewModelRW *models.Client
	ReviewModelRO *models.Client
}

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.Slaves)
	if err != nil {
		panic(err)
	}
	RWConn := sql.OpenDB(dialect.Postgres, rawRW)
	ROConn := sql.OpenDB(dialect.Postgres, rawRO)

	redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second)
	if redisCluster == nil || err != nil {
		panic(err)
	}

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