package consul

import (
	"fmt"
	"net/http"
	"strconv"
	"time"

	consul "github.com/hashicorp/consul/api"
)

type Service struct {
	Name       string
	Address    string
	appID      string
	domain     string
	pathPrefix string
	port       int
	ttl        time.Duration
	agent      *consul.Agent
	kv         *consul.KV
	catalog    *consul.Catalog
}

var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")

func NewService(servAddr, id, name, hostname, domain, pathPrefix string, appPort int) (*Service, error) {
	s := new(Service)
	s.Name = name
	s.Address = hostname
	s.appID = id
	s.domain = domain
	s.pathPrefix = pathPrefix
	s.port = appPort
	s.ttl = time.Second * 15

	client, err := consul.NewClient(newClientConfig(servAddr))
	if err != nil {
		return nil, err
	}
	s.agent = client.Agent()
	s.kv = client.KV()
	s.catalog = client.Catalog()

	return s, nil
}

func newClientConfig(serverAddr string) *consul.Config {
	conf := consul.DefaultConfig()
	conf.Address = serverAddr

	return conf
}

func (s *Service) GetID() string {
	return fmt.Sprintf("%s_%s", s.Name, s.appID)
}

func (s *Service) GetFullAddr() string {
	return fmt.Sprintf("http://%s:%d/", s.Address, s.port)
}

func (s *Service) Register() error {
	def := &consul.AgentServiceRegistration{
		ID:      s.GetID(),
		Name:    s.Name,
		Address: s.Address,
		Port:    s.port,
		Tags:    s.getTags(),
		Check: &consul.AgentServiceCheck{
			TTL:                            s.ttl.String(),
			DeregisterCriticalServiceAfter: "5s",
		},
	}

	if err := s.agent.ServiceRegister(def); err != nil {
		return err
	}

	go func(s *Service) { // startup register
		ticker := time.NewTicker(time.Millisecond * 100)
		for range ticker.C {
			if ok, _ := s.healthCheck(); ok {
				ticker.Stop()
			}
		}
	}(s)

	go func(s *Service) { // TTL
		interval := s.ttl - time.Second*2 // 2 seconds overhead
		ticker := time.NewTicker(interval)
		for range ticker.C {
			if _, err := s.healthCheck(); err != nil {
				fmt.Printf("TTL Error: %v\n", err)
			}
		}
	}(s)

	return nil
}
func (s *Service) Unregister() error {
	return s.agent.ServiceDeregister(s.GetID())
}

func (s *Service) KV() *consul.KV {
	return s.kv
}

func (s *Service) Catalog() *consul.Catalog {
	return s.catalog
}

func (s *Service) healthCheck() (bool, error) {
	alive := func() bool {
		client := &http.Client{}
		healthUrl := s.GetFullAddr() + "health"
		req, err := http.NewRequest(http.MethodGet, healthUrl, nil)
		if err != nil {
			return false
		}
		req.Header.Set("User-Agent", "Health Check")

		resp, err := client.Do(req)
		if err != nil {
			return false
		}
		defer resp.Body.Close()

		return resp.StatusCode == http.StatusOK
	}()

	if alive {
		if err := s.agent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
			return false, err
		}
		return true, nil
	}

	if err := s.agent.FailTTL("service:"+s.GetID(), ErrServiceUnavailable.Error()); err != nil {
		return false, err
	}
	return false, ErrServiceUnavailable
}

func (s *Service) getTags() []string {
	tags := []string{
		"traefik.enable=true",
		"traefik.http.routers." + s.Name + ".rule=PathPrefix(`" + s.pathPrefix + "`)",
		"traefik.http.routers." + s.Name + ".entryPoints=https",
		"traefik.http.routers." + s.Name + ".tls=true",
		"traefik.http.routers." + s.Name + ".service=" + s.Name,
		"traefik.http.routers." + s.Name + ".middlewares=auth_" + s.Name + ",requestid_" + s.Name + ",stripprefix_" + s.Name,
		"traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http",
		"traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.port),
		"traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false",
		"traefik.http.middlewares.auth_" + s.Name + ".auth.handlerURL=http://identity-svc/api/v1/traefik",
		// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authRequestHeaders=Cookie",
		// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authResponseHeaders=Set-Cookie, Server",
		// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.trustForwardHeader=true",
		"traefik.http.middlewares.requestid_" + s.Name + ".plugin.requestid.headerName=X-Request-ID",
		"traefik.http.middlewares.stripprefix_" + s.Name + ".stripprefix.prefixes=" + s.pathPrefix,
		"traefik.tls.certificates.certfile=/certs/client.cert",
		"traefik.tls.certificates.keyfile=/certs/client.key",
	}

	return tags
}