package auth

import (
	"os"
	"strings"
	"sync"
	"time"

	"gitea.hostxtra.co.uk/mrhid6/vantage/server/internal/models"
	"gitea.hostxtra.co.uk/mrhid6/vantage/server/internal/services"
	"github.com/gin-gonic/gin"
)

type cachedInstance struct {
	instance *models.Instance
	at       time.Time
}

var (
	instanceCacheMu sync.Mutex
	instanceCache   = map[string]cachedInstance{}
)

const instanceCacheTTL = 60 * time.Second

func appRootLabel() string {
	if v := os.Getenv("APP_ROOT_LABEL"); v != "" {
		return strings.ToLower(v)
	}
	return "vantage"
}

func hostSlug(host string) string {
	host = strings.ToLower(host)
	if i := strings.IndexByte(host, ':'); i >= 0 {
		host = host[:i]
	}
	root := appRootLabel()

	parts := strings.Split(host, ".")
	if len(parts) < 3 {
		return ""
	}
	if parts[1] != root {
		return ""
	}
	if parts[0] == root || parts[0] == "www" {
		return ""
	}
	return parts[0]
}

func InstanceFromHost(c *gin.Context) (*models.Instance, bool) {
	slug := hostSlug(c.Request.Host)
	if slug == "" {
		return nil, false
	}
	instanceCacheMu.Lock()
	if e, ok := instanceCache[slug]; ok && time.Since(e.at) < instanceCacheTTL {
		instanceCacheMu.Unlock()
		return e.instance, e.instance != nil
	}
	instanceCacheMu.Unlock()

	inst, err := services.GetInstanceBySlug(slug)
	if err != nil || inst == nil {

		return nil, false
	}
	instanceCacheMu.Lock()
	instanceCache[slug] = cachedInstance{instance: inst, at: time.Now()}
	instanceCacheMu.Unlock()
	return inst, true
}
