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 {
	BaseFetcher
	Repos []string
}

func (f *GiteaFetcher) Name() string {
	return "Gitea"
}

func (f *GiteaFetcher) Fetch() []Entry {
	var entries []Entry

	for _, repo := range f.Repos {
		repo = strings.TrimSpace(repo)
		if repo == "" {
			continue
		}

		req := FetcherRequest{
			BaseURL: f.BaseURL,
			Path:    fmt.Sprintf("/api/v1/repos/%s/commits?limit=%d", repo, f.ContentLimit),
			Method:  http.MethodGet,
			Headers: map[string]string{
				"Authorization": "token " + f.Token,
			},
		}

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

		if len(response) == 0 {
			continue
		}

		for _, content := range response {
			cacheKey := "gitea_commit_" + url.QueryEscape(f.BaseURL+repo+"_"+content.Sha)

			entry := f.TryCreateEntry(
				cacheKey,
				content.Sha,
				fmt.Sprintf("📝 [%s] - (%s) %s", f.Name(), repo, content.Commit.Message),
				content.HTMLURL,
			)

			if entry != nil {
				entries = append(entries, *entry)
			}
		}
	}

	return entries
}
