package lib

import (
	"fmt"
	"net/http"
)

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

type RedmineFetcher struct {
	BaseFetcher
}

func (f *RedmineFetcher) Name() string {
	return "Redmine"
}

func (f *RedmineFetcher) Fetch() []Message {
	var messages []Message
	path := fmt.Sprintf("/issues.json?limit=%d&sort=updated_on:desc", f.ContentLimit)
	req := FetcherRequest{
		BaseURL: f.BaseURL,
		Path:    path,
		Method:  http.MethodGet,
		Headers: map[string]string{
			"X-Redmine-API-Key": f.Token,
		},
	}

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

	if len(response.Issues) == 0 {
		return nil
	}

	for _, content := range response.Issues {
		message := f.TryCreateMessage(
			"redmine",
			fmt.Sprintf("redmine_%d", content.ID),
			content.UpdatedOn,
			fmt.Sprintf("🎫 [%s] - #%d %s", f.Name(), content.ID, content.Subject),
			fmt.Sprintf("%s/issues/%d", f.BaseURL, content.ID),
		)
		if message != nil {
			messages = append(messages, *message)
		}
	}

	return messages
}
