package page

import (
	"context"
	"log/slog"
	"strings"
)

type PageHeader struct {
	UID           string
	Title         string
	CoverImageUID string
	md            []byte // markdown of the page //markdown of the page
}

type Page struct {
	PageHeader
	Content string
	Images  []Image
}

func (s *Service) GetPages(ctx context.Context) (pages []PageHeader, err error) {
	paths, err := s.fs.ReadDir("/")
	if err != nil {
		return
	}

	for _, path := range paths {
		if strings.HasPrefix(path.Name(), ".") || // hidden files
			strings.HasPrefix(path.Name(), "_") { // hidden pages
			continue
		}
		page, err := s.getPageHeaders(ctx, path.Name())
		if err != nil { // just ignore missing pages
			slog.Error("could not open path", "path", path.Name(), "err", err)
			continue
		}
		pages = append(pages, page)
	}

	return
}

func (s *Service) GetPage(ctx context.Context, uid string) (page Page, err error) {
	p, err := s.getPageHeaders(ctx, uid)
	if err != nil {
		return
	}

	html, imgs, err := s.getHTML(ctx, p)
	if err != nil {
		return
	}

	page = Page{
		PageHeader: p,
		Content:    string(html),
		Images:     imgs,
	}
	return
}
