package consul

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

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

type Service struct {
	AppID       string
	Name        string
	Domain      string
	Address     string
	Port        int
	TTL         time.Duration
	ConsulAgent *consul.Agent
}

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

func NewService(servAddr, id, name, hostname, domain string, appPort int) (*Service, error) {
	s := new(Service)
	s.AppID = id
	s.Name = name
	s.Address = hostname
	s.Domain = domain
	s.Port = appPort
	s.TTL = time.Second * 15

	client, err := consul.NewClient(newClientConfig(servAddr))
	if err != nil {
		return nil, err
	}
	s.ConsulAgent = client.Agent()

	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(),
		},
	}

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

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

	go func() { // TTL
		interval := s.TTL - time.Second*3
		ticker := time.NewTicker(interval)
		for range ticker.C {
			fmt.Println("HC call: ", time.Now().String())
			_, err := s.healthCheck()
			if err != nil {
				fmt.Printf("TTL Error: %v\n", err)
			}
		}
	}()

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

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.ConsulAgent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
			return false, err
		}
		return true, nil
	}

	if err := s.ConsulAgent.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=Host(`" + s.Domain + "`)",
		"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=compress,requestid",
		"traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http",
		"traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.Port),
		"traefik.http.middlewares.compress.compress=true",
		"traefik.http.middlewares.requestid.plugin.requestid.headerName=X-Request-ID",
		// "traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false",
		// "traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + "=" + bFullAddr,
		// "traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + ".url=" + bFullAddr,
		// "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.path=/health",
		// "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.interval=10s",
	}

	return tags
}