package checks

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type VersionConfig struct {
	Enabled bool `yaml:"enabled"`
	Version string
}

type Version struct {
	Config VersionConfig
}

func (h Version) Execute() (ok bool, data interface{}, err error) {
	if h.Config.Enabled == false {
		return true, nil, nil
	}
	resp, err := http.Get("https://git.keks.cloud/api/v1/repos/kekskurse/http-server-status/releases?limit=1")
	defer resp.Body.Close()

	var g []struct {
		TagName string `json:"tag_name"`
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return false, nil, err
	}

	json.Unmarshal(body, &g)

	if g[0].TagName == fmt.Sprintf("v%v", h.Config.Version) {
		return true, map[string]string{"version": g[0].TagName}, nil
	}
	return false, map[string]string{"version": g[0].TagName}, nil
}

func (h Version) Name() string {
	return "Version"
}