package svc

import (
	stdsql "database/sql"
	"fmt"
	"strings"
	"time"

	"ariga.io/entcache"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	_ "github.com/jackc/pgx/v5/stdlib"
	"github.com/zeromicro/go-zero/core/logx"
	"juwan-backend/app/order/rpc/internal/config"
	"juwan-backend/app/order/rpc/internal/models"
	"juwan-backend/app/snowflake/rpc/snowflake"
	"juwan-backend/common/redisx"
	"juwan-backend/common/snowflakex"
	"juwan-backend/pkg/adapter"
)

type ServiceContext struct {
	Config        config.Config
	Snowflake     snowflake.SnowflakeServiceClient
	OrderModelsRW *models.Client
	OrderModelsRO *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 {
		logx.Errorf("failed to connect to Redis cluster: %v", err)
		panic(err)
	}
	// snowflakex.NewClient(c.SnowflakeRpcConf)

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

	entLogFn := func(v ...any) {
		logx.Infof("[ent][order] %s", fmt.Sprint(v...))
	}

	rwOpts := []models.Option{models.Driver(RWDrv), models.Log(entLogFn)}
	roOpts := []models.Option{models.Driver(RODrv), models.Log(entLogFn)}
	if strings.EqualFold(c.Log.Level, "debug") {
		rwOpts = append(rwOpts, models.Debug())
		roOpts = append(roOpts, models.Debug())
	}

	return &ServiceContext{
		Config:        c,
		Snowflake:     snowflakex.NewClient(c.SnowflakeRpcConf),
		OrderModelsRW: models.NewClient(rwOpts...),
		OrderModelsRO: models.NewClient(roOpts...),
	}
}
