package svc

import (
	stdsql "database/sql"
	"fmt"
	"juwan-backend/app/shop/rpc/internal/config"
	"juwan-backend/app/shop/rpc/internal/models"
	"juwan-backend/app/snowflake/rpc/snowflake"
	"juwan-backend/app/users/rpc/usercenter"
	"juwan-backend/common/redisx"
	"juwan-backend/common/snowflakex"
	"juwan-backend/pkg/adapter"
	"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"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config      config.Config
	Snowflake   snowflake.SnowflakeServiceClient
	UsersRpc    usercenter.Usercenter
	ShopModelRW *models.Client
	ShopModelRO *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][shop] %s", fmt.Sprint(v...))
	}

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

	return &ServiceContext{
		Config:      c,
		Snowflake:   snowflakex.NewClient(c.SnowflakeRpcConf),
		UsersRpc:    usercenter.NewUsercenter(zrpc.MustNewClient(c.UsersRpcConf)),
		ShopModelRO: models.NewClient(roModelOpts...),
		ShopModelRW: models.NewClient(rwModelOpts...),
	}
}
