package svc

import (
	"backend/internal/config"
	"backend/pkg/chat/domain/usecase"
	repo "backend/pkg/chat/repository"
	uc "backend/pkg/chat/usecase"
	"backend/pkg/library/cassandra"
	"backend/pkg/library/centrifugo"
	errs "backend/pkg/library/errors"
	"fmt"
)

func MustMessageUseCase(c *config.Config, logger errs.Logger) usecase.MessageUseCase {
	// 初始化 Cassandra DB
	cassandraDB, err := initCassandraDB(c)
	if err != nil {
		panic(fmt.Sprintf("failed to initialize Cassandra DB: %v", err))
	}

	// 初始化 Message Repository
	messageRepo := repo.MustMessageRepository(repo.MessageRepositoryParam{
		DB:       cassandraDB,
		Keyspace: c.Cassandra.Keyspace,
	})

	// 初始化 Room Repository
	roomRepo := repo.MustRoomRepository(repo.RoomRepositoryParam{
		DB:       cassandraDB,
		Keyspace: c.Cassandra.Keyspace,
	})

	// 初始化 Centrifugo Client
	msgClient := centrifugo.NewClientWithConfig(centrifugo.HighPerformanceConfig(c.Centrifugo.APIURL, c.Centrifugo.APIKey))

	return uc.NewMessageUseCase(uc.MessageUseCaseParam{
		MessageRepo: messageRepo,
		RoomRepo:    roomRepo,
		MsgClient:   msgClient,
		Logger:      logger,
	})
}

// initCassandraDB 初始化 Cassandra 資料庫連接
func initCassandraDB(c *config.Config) (*cassandra.DB, error) {
	if len(c.Cassandra.Hosts) == 0 {
		return nil, fmt.Errorf("cassandra hosts are required")
	}

	opts := []cassandra.Option{
		cassandra.WithHosts(c.Cassandra.Hosts...),
	}

	if c.Cassandra.Port > 0 {
		opts = append(opts, cassandra.WithPort(c.Cassandra.Port))
	}

	if c.Cassandra.Keyspace != "" {
		opts = append(opts, cassandra.WithKeyspace(c.Cassandra.Keyspace))
	}

	if c.Cassandra.UseAuth {
		opts = append(opts, cassandra.WithAuth(c.Cassandra.Username, c.Cassandra.Password))
	}

	return cassandra.New(opts...)
}
