package database

import (
	"database/sql"
	"fmt"

	"github.com/russross/blackfriday/v2"
)

type Post struct {
	ID               int
	Title            string `db:"post_title"`
	Content          string
	Date             string
	MarkdownContent  string         `db:"markdown_content"`
	GemtextContent   sql.NullString `db:"gemtext_content"`
	TitleSlug        string         `db:"title_slug"`
	Year, Month, Day int
}

func (p *Post) GemtextPage() string {
	return fmt.Sprintf("# %s\n\n", p.Title) + p.GemtextContent.String + "\n\n" + p.Date

}

func (p *Post) HTMLPage() string {
	extensions := blackfriday.CommonExtensions | blackfriday.HardLineBreak
	result := fmt.Sprintf("<h1>%s</h1>\n%s", p.Title, blackfriday.Run([]byte(p.MarkdownContent), blackfriday.WithExtensions(extensions)))
	result += fmt.Sprintf("%s", p.Date)
	return result
}

func GetPost(id int) (*Post, error) {
	db := GetDB()
	post := &Post{}
	err := db.Get(post, "SELECT id, post_title, date, markdown_content, gemtext_content, title_slug, year, month, day FROM posts WHERE id = ?", id)
	if err != nil {
		return nil, err
	}
	return post, nil
}
