package main

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

// https://codeberg.org/api/v1/repos/forgejo/forgejo/releases?limit=1
type Forgejo struct {
}

type forgejoAPIResponse struct {
	TagName string `json:"tag_name"`
}

func (g Forgejo) getLastVersion(s software) (string, error) {
	url := fmt.Sprintf("%s/api/v1/repos/%s/releases?limit=1", s.Data["server"], s.Data["repo"])

	res, err := http.Get(url)
	if err != nil {
		return "", err
	}
	body, err := io.ReadAll(res.Body)
	if err != nil {
		return "", err
	}

	var data []forgejoAPIResponse

	err = json.Unmarshal(body, &data)
	if err != nil {
		return "", err
	}

	if len(data) != 1 {
		return "", errors.New("cant find any release")
	}

	return data[0].TagName, nil
}
