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
		}

		repo = strings.TrimSpace(repo)
		path := fmt.Sprintf("/api/v1/repos/%s/commits", repo)

		headers := map[string]string{}
		if f.Token != "" {
			headers["Authorization"] = "token " + f.Token
		}

		req := FetcherRequest{
			BaseURL: f.BaseURL,
			Path:    path,
			Method:  http.MethodGet,
			Headers: headers,
		}

		var r GiteaResponse

		if err := req.Run(&r); err != nil {
			continue
		}

		if len(r) == 0 {
			continue
		}

		commit := r[0]
		cacheKey := "gitea_" + url.QueryEscape(f.BaseURL+path)

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