package lib

import (
	"fmt"
	"net/http"
)

type RedmineResponse struct {
	Issues []struct {
		ID        int
		UpdatedOn string
		Subject   string
	}
}

type RedmineFetcher struct {
	BaseURL string
	Key     string
	Cache   *Cache
}

func (f RedmineFetcher) Fetch() []Entry {
	req := FetcherRequest{
		BaseURL: f.BaseURL,
		Path:    "/issues.json?limit=1&sort=updated_on:desc",
		Method:  http.MethodGet,
		Headers: map[string]string{
			"X-Redmine-API-Key": f.Key,
		},
	}

	var r RedmineResponse

	if err := req.Run(&r); err != nil {
		return []Entry{}
	}

	if len(r.Issues) == 0 {
		return []Entry{}
	}

	i := r.Issues[0]
	if f.Cache.TryUpdate("redmine", i.UpdatedOn) {
		url := fmt.Sprintf("%s/issues/%d", f.BaseURL, i.ID)
		return []Entry{{
			Title: fmt.Sprintf("🎫 [Redmine] - #%d %s", i.ID, i.Subject),
			URL:   url,
		}}
	}
	return []Entry{}
}
