package main

import (
	"forge.cadoles.com/wpetit/gitea-kan/internal/config"
	"forge.cadoles.com/wpetit/gitea-kan/internal/repository"
	stormRepo "forge.cadoles.com/wpetit/gitea-kan/internal/repository/storm"
	"github.com/asdine/storm"
	"github.com/gorilla/sessions"
	"github.com/pkg/errors"
	"gitlab.com/wpetit/goweb/service"
	"gitlab.com/wpetit/goweb/service/session"
	"gitlab.com/wpetit/goweb/session/gorilla"
	"go.etcd.io/bbolt"
)

func getServiceContainer(conf *config.Config) (*service.Container, error) {
	// Initialize and configure service container
	ctn := service.NewContainer()

	// Create and initialize HTTP session service provider
	cookieStore, err := gorilla.CreateCookieSessionStore(64, 32, &sessions.Options{
		Path:     "/",
		HttpOnly: true,
	})
	if err != nil {
		return nil, errors.Wrap(err, "could not create cookie store")
	}

	ctn.Provide(
		session.ServiceName,
		gorilla.ServiceProvider("gitea-kan", cookieStore),
	)

	// Create and expose config service provider
	ctn.Provide(config.ServiceName, config.ServiceProvider(conf))

	// Load Storm database
	db, err := storm.Open(conf.Data.DBPath, storm.BoltOptions(
		0660,
		&bbolt.Options{},
	))
	if err != nil {
		return nil, errors.Wrap(err, "could not open database")
	}

	boardsRepository := stormRepo.NewBoardRepository(db)
	if err := boardsRepository.Init(); err != nil {
		return nil, errors.Wrap(err, "could not init boards repository")
	}

	ctn.Provide(repository.ServiceName, repository.ServiceProvider(
		repository.NewRepository(
			boardsRepository,
		),
	))

	return ctn, nil
}