package lib

import (
	"fmt"
	"net/http"
	"strconv"
)

type GravResponse struct {
	Pages []struct {
		Route    string `json:"route"`
		Title    string `json:"title"`
		Modified int64  `json:"modified"`
	} `json:"pages"`
}

type GravFetcher struct {
	BaseFetcher
}

func (f *GravFetcher) Name() string {
	return "Grav"
}

func (f *GravFetcher) Fetch() []Message {
	var messages []Message

	req := FetcherRequest{
		BaseURL: f.BaseURL,
		Path:    fmt.Sprintf("/api-custom/updates.json?limit=%d", f.ContentLimit),
		Method:  http.MethodGet,
	}

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

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

	for _, content := range response.Pages {
		message := f.TryCreateMessage(
			"grav",
			"grav_"+content.Route,
			strconv.FormatInt(content.Modified, 10),
			fmt.Sprintf("📖 [%s] - %s", f.Name(), content.Title),
			fmt.Sprintf("%s%s", f.BaseURL, content.Route),
		)

		if message != nil {
			messages = append(messages, *message)
		}
	}

	return messages
}
