package routers

import (
	"context"
	"fmt"
	"reflect"
	"runtime"
	"time"

	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/web"
	"code.gitlink.org.cn/Gitlink/gitea_hat.git/models/migrations"
	api_hat "code.gitlink.org.cn/Gitlink/gitea_hat.git/routers/hat"
)

func mustInitCtx(ctx context.Context, fn func(ctx context.Context) error) {
	err := fn(ctx)
	if err != nil {
		ptr := reflect.ValueOf(fn).Pointer()
		fi := runtime.FuncForPC(ptr)
		log.Fatal("%s(ctx) failed: %v", fi.Name(), err)
	}
}

func GlobalInitInstalled(ctx context.Context) {
	mustInitCtx(ctx, InitDBEngine)
}

func InitHatRouters(ctx context.Context, e *web.Route) *web.Route {

	e.Mount("/api/hat", api_hat.Routers(ctx))
	return e
}

func InitDBEngine(ctx context.Context) (err error) {
	log.Info("Beginning hat ORM engine initialization.")
	for i := 0; i < setting.Database.DBConnectRetries; i++ {
		select {
		case <-ctx.Done():
			return fmt.Errorf("Aborted due to shutdown:\nin retry hat ORM engine initialization")
		default:
		}
		log.Info("hat ORM engine initialization attempt #%d/%d...", i+1, setting.Database.DBConnectRetries)
		if err = db.InitEngineWithMigration(ctx, migrations.Migrate); err == nil {
			break
		} else if i == setting.Database.DBConnectRetries-1 {
			return err
		}
		log.Error("hat ORM engine initialization attempt #%d/%d failed. Error: %v", i+1, setting.Database.DBConnectRetries, err)
		log.Info("Backing off for %d seconds", int64(setting.Database.DBConnectBackoff/time.Second))
		time.Sleep(setting.Database.DBConnectBackoff)
	}
	db.HasEngine = true
	return nil
}
