package lib

import (
	"fmt"
	"net/http"
)

type WikiResponse struct {
	Data struct {
		Pages struct {
			List []struct {
				UpdatedAt string
				Title     string
				Path      string
			}
		}
	}
}

type WikiFetcher struct {
	BaseFetcher
}

func (f *WikiFetcher) Name() string {
	return "WikiJS"
}

func (f *WikiFetcher) Fetch() []Message {
	var messages []Message
	query := fmt.Sprintf(`{"query":"{ pages { list(orderBy: UPDATED, orderByDirection: DESC, limit: %d){ path, updatedAt, title }}}"}`, f.ContentLimit)

	req := FetcherRequest{
		BaseURL: f.BaseURL,
		Path:    "/graphql",
		Method:  http.MethodPost,
		Headers: map[string]string{
			"Authorization": "Bearer " + f.Token,
			"Content-Type":  "application/json",
		},
		Body: []byte(query),
	}

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

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

	for _, content := range response.Data.Pages.List {
		message := f.TryCreateMessage(
			"wiki",
			"wiki_"+content.Path,
			content.UpdatedAt,
			fmt.Sprintf("📖 [%s] - %s", f.Name(), content.Title),
			fmt.Sprintf("%s/%s", f.BaseURL, content.Path),
		)

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

	return messages
}
