package authorizationapp

import (
	"git.gocasts.ir/ebhomengo/niki/authorizationapp/delivery/http"
	"git.gocasts.ir/ebhomengo/niki/domain/authorization/repository"
	"git.gocasts.ir/ebhomengo/niki/domain/authorization/service"
	cfgloader "git.gocasts.ir/ebhomengo/niki/pkg/cfg_loader"
	mySql "git.gocasts.ir/ebhomengo/niki/pkg/database/mysql"
	"git.gocasts.ir/ebhomengo/niki/pkg/httpserver"
	"git.gocasts.ir/ebhomengo/niki/pkg/path"
	"log"
	"os"
	"path/filepath"
)

type Config struct {
	HTTPServer httpserver.Config `koanf:"http_server"`
	MySQLDB    mySql.Config      `koanf:"mariadb"`
}
type Application struct {
	RoleRepo             *repository.RoleRepo
	AuthorizationService service.Authorization
	RoleHandler          http.RoleHandler
	RoleServer           http.RoleServer
}

func (a Application) Setup() Application {
	appConfig := a.getYamlConfigPath()
	db := mySql.New(appConfig.MySQLDB)
	roleRepo := repository.New(db)
	authorizationService := service.NewAuthorization(roleRepo)
	roleHandler := http.NewRoleHandler(authorizationService)
	server := http.NewRoleServer(appConfig.HTTPServer, roleHandler)

	return Application{
		RoleRepo:             roleRepo,
		AuthorizationService: authorizationService,
		RoleHandler:          roleHandler,
		RoleServer:           server,
	}
}

func (a Application) Start() {
	// todo implement role service start
}

func (a Application) getYamlConfigPath() Config {
	var appConfig Config

	projectRoot, err := path.PathProjectRoot()
	if err != nil {
		log.Fatalf("Error finding project root: %v", err)
	}

	defaultConfig := filepath.Join(projectRoot, "deploy", "authorization", "config.yml")
	_, err = os.Stat(defaultConfig)
	if err != nil {
		log.Fatal(err.Error())
	}

	options := cfgloader.Option{
		Prefix:       "AUTHORIZATION_",
		Delimiter:    ".",
		Separator:    "__",
		YamlFilePath: defaultConfig,
		CallbackEnv:  nil,
	}
	err = cfgloader.Load(options, &appConfig)
	if err != nil {
		log.Fatalf("failed loading authorization config: %v", err)
	}
	return appConfig
}
