package lib

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

type GiteaResponse []struct {
	Sha     string `json:"sha"`
	HTMLURL string `json:"html_url"`
	Commit  struct {
		Message string `json:"message"`
	} `json:"commit"`
}

type GiteaFetcher struct {
	BaseURL string
	Token   string
	Repos   []string
	Cache   *Cache
}

func (f GiteaFetcher) Fetch() []Entry {
	var messages []Entry

	for _, repo := range f.Repos {
		if repo == "" {
			continue
		}
		giteaURL := fmt.Sprintf("%s/api/v1/repos/%s/commits", f.BaseURL, strings.TrimSpace(repo))
		req, _ := http.NewRequest("GET", giteaURL, nil)
		if f.Token != "" {
			req.Header.Set("Authorization", "token "+f.Token)
		}

		var r GiteaResponse

		if err := getJSON(req, &r); err != nil {
			continue
		}

		if len(r) == 0 {
			continue
		}

		commit := r[0]

		if f.Cache.TryUpdate("gitea_"+url.QueryEscape(giteaURL), commit.Sha) {
			messages = append(messages, Entry{
				Title: fmt.Sprintf("📝 [Gitea] - (%s) %s", repo, commit.Commit.Message),
				URL:   commit.HTMLURL,
			})
		}
	}
	return messages
}
