package lib

import (
	"fmt"
	"net/http"
)

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

type WikiFetcher struct {
	BaseURL string
	Token   string
	Cache   *Cache
}

func (f WikiFetcher) Fetch() []Entry {
	q := `{"query":"{ pages { list(orderBy: UPDATED, orderByDirection: DESC, limit: 1){ path, updatedAt, title }}}"}`

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

	var r WikiResponse

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

	if len(r.Data.Pages.List) == 0 {
		return []Entry{}
	}
	u := r.Data.Pages.List[0]
	if f.Cache.TryUpdate("wiki", u.UpdatedAt) {
		url := fmt.Sprintf("%s/%s", f.BaseURL, u.Path)
		return []Entry{{
			Title: fmt.Sprintf("📖 [WikiJS] - %s", u.Title),
			URL:   url,
		}}
	}
	return []Entry{}
}
