// Filename: internal/domain/proxy/module.go
package proxy

import (
	"gemini-balancer/internal/models"
	"gemini-balancer/internal/settings"
	"gemini-balancer/internal/store"
	"gemini-balancer/internal/syncer"
	"gemini-balancer/internal/task"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type Module struct {
	manager *manager
	handler *handler
}

func NewModule(gormDB *gorm.DB, store store.Store, settingsManager *settings.SettingsManager, taskReporter task.Reporter, logger *logrus.Logger) (*Module, error) {
	loader := newManagerLoader(gormDB)
	cacheSyncer, err := syncer.NewCacheSyncer(loader, store, "proxies:cache_invalidation", logger)
	if err != nil {
		return nil, err
	}
	manager := newManager(gormDB, cacheSyncer, taskReporter, store, logger.WithField("domain", "proxy"))
	handler := newHandler(gormDB, manager, store, settingsManager)
	return &Module{
		manager: manager,
		handler: handler,
	}, nil
}

func (m *Module) AssignProxyIfNeeded(apiKey *models.APIKey) (*models.ProxyConfig, error) {
	return m.manager.assignProxyIfNeeded(apiKey)
}

func (m *Module) RegisterRoutes(router *gin.RouterGroup) {
	m.handler.registerRoutes(router)
}

func (m *Module) Stop() {
	m.manager.stop()
}
