package svc

import (
	"context"
	"log"
	"time"

	"juwan-backend/app/chat/api/internal/config"
	"juwan-backend/app/chat/chatcore"

	"github.com/redis/go-redis/v9"
	"github.com/wwweww/go-wst/stateless"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ServiceContext struct {
	Config   config.Config
	Store    chatcore.Store
	MsgStore *stateless.MemoryStore
}

func NewServiceContext(c config.Config) *ServiceContext {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(c.Mongo.URI))
	if err != nil {
		log.Fatalf("mongo connect: %v", err)
	}
	if err := mongoClient.Ping(ctx, nil); err != nil {
		log.Fatalf("mongo ping: %v", err)
	}

	db := mongoClient.Database(c.Mongo.Database)
	mongoStore, err := chatcore.NewMongoStore(db)
	if err != nil {
		log.Fatalf("mongo store: %v", err)
	}

	rdb := redis.NewClient(&redis.Options{
		Addr:     c.Redis.Addr,
		Password: c.Redis.Password,
		DB:       c.Redis.DB,
	})
	if err := rdb.Ping(ctx).Err(); err != nil {
		log.Fatalf("redis ping: %v", err)
	}

	return &ServiceContext{
		Config:   c,
		Store:    chatcore.NewCachedStore(mongoStore, rdb),
		MsgStore: stateless.NewMemoryStore(),
	}
}
