package depenv

import (
	"fmt"
	"os"
)

var manageServers = map[DeploymentEnvironment]string{
	DeployDevel: "https://manage.askdev.grundclock.com",
	DeployTest:  "https://manage.beta.grundclock.com",
	DeployProd:  "https://manage.ntppool.org",
}

var apiServers = map[DeploymentEnvironment]string{
	DeployDevel: "https://dev-api.ntppool.dev",
	DeployTest:  "https://beta-api.ntppool.dev",
	DeployProd:  "https://api.ntppool.dev",
}

// var validationServers = map[DeploymentEnvironment]string{
// 	DeployDevel: "https://v.ntp.dev/d/",
// 	DeployTest:  "https://v.ntp.dev/b/",
// 	DeployProd:  "https://v.ntp.dev/p/",
// }

const (
	DeployUndefined DeploymentEnvironment = iota
	DeployDevel
	DeployTest
	DeployProd
)

type DeploymentEnvironment uint8

func DeploymentEnvironmentFromString(s string) DeploymentEnvironment {
	switch s {
	case "devel", "dev":
		return DeployDevel
	case "test", "beta":
		return DeployTest
	case "prod":
		return DeployProd
	default:
		return DeployUndefined
	}
}

func (d DeploymentEnvironment) String() string {
	switch d {
	case DeployProd:
		return "prod"
	case DeployTest:
		return "test"
	case DeployDevel:
		return "devel"
	default:
		panic("invalid DeploymentEnvironment")
	}
}

func (d DeploymentEnvironment) APIHost() string {
	if apiHost := os.Getenv("API_HOST"); apiHost != "" {
		return apiHost
	}
	return apiServers[d]
}

func (d DeploymentEnvironment) ManageURL(path string) string {
	return manageServers[d] + path
}

func (d DeploymentEnvironment) MonitorDomain() string {
	return d.String() + ".mon.ntppool.dev"
}

func (d *DeploymentEnvironment) UnmarshalText(text []byte) error {
	s := string(text)
	if s == "" {
		return nil
	}
	env := DeploymentEnvironmentFromString(s)
	if env == DeployUndefined {
		return fmt.Errorf("invalid deployment environment: %s", s)
	}
	*d = env
	return nil
}