package handlers

import (
	"net/http"
	"os"
	"path"

	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
)

// DocsHandler serves API docs for the gateway
func DocsHandler() http.Handler {
	fp := envtool.GetEnv("DOCS", "")
	if fp == "" {
		return nil
	}

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Get the requested path
		reqPath := r.URL.Path
		if reqPath == "" || reqPath == "/" {
			reqPath = "/index.html"
		}

		// Build full file path
		fullPath := path.Join(fp, reqPath)

		// Check if it's a directory, serve index.html
		info, err := os.Stat(fullPath)
		if err == nil && info.IsDir() {
			fullPath = path.Join(fullPath, "index.html")
		}

		http.ServeFile(w, r, fullPath)
	})
}
