package handlers

import (
	"embed"
	"net/http"
	"path/filepath"

	"git.warky.dev/wdevs/whatshooked/pkg/logging"
)

//go:embed static/*
var staticFiles embed.FS

// ServeIndex serves the landing page
func (h *Handlers) ServeIndex(w http.ResponseWriter, r *http.Request) {
	// Only serve index on root path
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	content, err := staticFiles.ReadFile("static/index.html")
	if err != nil {
		logging.Error("Failed to read index.html", "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	writeBytes(w, content)
}

// ServeTermsOfService serves the terms of service page
func (h *Handlers) ServeTermsOfService(w http.ResponseWriter, r *http.Request) {
	content, err := staticFiles.ReadFile("static/terms-of-service.html")
	if err != nil {
		logging.Error("Failed to read terms-of-service.html", "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	writeBytes(w, content)
}

// ServePrivacyPolicy serves the privacy policy page
func (h *Handlers) ServePrivacyPolicy(w http.ResponseWriter, r *http.Request) {
	content, err := staticFiles.ReadFile("static/privacy-policy.html")
	if err != nil {
		logging.Error("Failed to read privacy-policy.html", "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	writeBytes(w, content)
}

// ServeStatic serves static files (logo, etc.)
func (h *Handlers) ServeStatic(w http.ResponseWriter, r *http.Request) {
	// Get the file path from URL
	filename := filepath.Base(r.URL.Path)
	filePath := filepath.Join("static", filename)

	content, err := staticFiles.ReadFile(filePath)
	if err != nil {
		logging.Error("Failed to read static file", "path", filePath, "error", err)
		http.NotFound(w, r)
		return
	}

	// Set content type based on file extension
	ext := filepath.Ext(filePath)
	switch ext {
	case ".png":
		w.Header().Set("Content-Type", "image/png")
	case ".jpg", ".jpeg":
		w.Header().Set("Content-Type", "image/jpeg")
	case ".svg":
		w.Header().Set("Content-Type", "image/svg+xml")
	case ".html":
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
	case ".css":
		w.Header().Set("Content-Type", "text/css")
	case ".js":
		w.Header().Set("Content-Type", "application/javascript")
	}

	// Cache static assets for 1 hour
	w.Header().Set("Cache-Control", "public, max-age=3600")
	w.WriteHeader(http.StatusOK)
	writeBytes(w, content)
}
