package main

import (
	"compress/gzip"
	"net/http"
	"os"
	"time"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"

	"a.yandex-team.ru/library/go/core/log"
	"a.yandex-team.ru/library/go/core/log/zap"
	"a.yandex-team.ru/library/go/yandex/blackbox/httpbb"
	"a.yandex-team.ru/library/go/yandex/tvm/tvmtool"

	"a.yandex-team.ru/intranet/legacy/staff-api/internal/api"
	"a.yandex-team.ru/intranet/legacy/staff-api/internal/api/handler"
	"a.yandex-team.ru/intranet/legacy/staff-api/internal/database"
	"a.yandex-team.ru/intranet/legacy/staff-api/internal/idm"
	"a.yandex-team.ru/intranet/legacy/staff-api/internal/user"
)

func newConfig() *api.Config {
	if os.Getenv("DEPLOY_STAGE_ID") == "tools_staff-api_production" {
		return &api.Config{
			LogLevel: log.TraceLevel,
		}
	} else {
		return &api.Config{
			LogLevel: log.DebugLevel,
		}
	}
}

func main() {
	config := newConfig()

	logger, err := zap.NewDeployLogger(config.LogLevel)
	if err != nil {
		panic(err)
	}

	tvmClient, err := tvmtool.NewAnyClient(tvmtool.WithLogger(logger))
	if err != nil {
		logger.Fatal("unable to init tvm client, use tvmtool for development", log.Error(err))
	}

	bbClient, err := httpbb.NewIntranet(
		httpbb.WithLogger(logger),
		httpbb.WithTVM(tvmClient),
	)
	if err != nil {
		logger.Fatal("unable to init blackbox client", log.Error(err))
	}

	db := database.NewClient(logger)
	err = db.InitDBConnection()
	if err != nil {
		logger.Fatal("unable to init database connection", log.Error(err))
	}

	r := chi.NewRouter()

	r.Use(middleware.Heartbeat("/ping"))
	r.Use(middleware.Timeout(60 * time.Second))
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middleware.Compress(gzip.BestSpeed, "application/json"))
	r.Use(user.SetUserAndServiceID(logger, bbClient, tvmClient))

	r.Get("/test", handler.Test)

	r.Mount("/idm", idm.GetRoutes(logger, db))
	r.Mount("/v3", api.GetRoutes(db))
	// http.Handle("/v3/", checkAuth(apiHandler))

	if err := http.ListenAndServe(":80", r); err != nil {
		logger.Fatal("unable to start listening", log.Error(err))
	}
}
