package utils

import (
	"bytes"
	"html/template"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/joho/godotenv"
)

// Helper functions for templates
var templateFuncs = template.FuncMap{
	"add": func(a, b int) int {
		return a + b
	},
	"sub": func(a, b int) int {
		return a - b
	},
	"eq": func(a, b interface{}) bool {
		return a == b
	},
	"pageRange": func(currentPage, totalPages int) []int {
		// Generate page numbers to show (max 7 pages)
		start := currentPage - 3
		end := currentPage + 3

		if start < 1 {
			end += 1 - start
			start = 1
		}
		if end > totalPages {
			start -= end - totalPages
			end = totalPages
		}
		if start < 1 {
			start = 1
		}

		var pages []int
		for i := start; i <= end; i++ {
			pages = append(pages, i)
		}
		return pages
	},
}

func Render(w http.ResponseWriter, tmpl string, data interface{}) {
	// Load .env file
	err := godotenv.Load() // or specify path: godotenv.Load("/path/to/.env")
	if err != nil {
		log.Fatalf("Error loading .env file: %v", err)
	}

	// Get individual components from environment variables
	TemplatesURL := os.Getenv("TEMPLATES_URL")

	// Paths for layout + page templates
	layout := filepath.Join(TemplatesURL, "layout.html")
	page := filepath.Join(TemplatesURL, tmpl)

	// Parse files with helper functions
	tmpls, err := template.New("").Funcs(templateFuncs).ParseFiles(layout, page)
	if err != nil {
		http.Error(w, "Template parsing error: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// Render to buffer first (catch errors before writing response)
	var buf bytes.Buffer
	err = tmpls.ExecuteTemplate(&buf, "layout", data)
	if err != nil {
		http.Error(w, "Template execution error: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// Write final HTML to response
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	buf.WriteTo(w)
}
