package handlers

import (
	"net/http"

	"git.haelnorr.com/h/golib/hws"
	"git.haelnorr.com/h/oslstats/internal/view/page"
)

// func ErrorPage(
// 	error hws.HWSError,
// ) (hws.ErrorPage, error) {
// 	messages := map[int]string{
// 		400: "The request you made was malformed or unexpected.",
// 		401: "You need to login to view this page.",
// 		403: "You do not have permission to view this page.",
// 		404: "The page or resource you have requested does not exist.",
// 		500: `An error occured on the server. Please try again, and if this
//         continues to happen contact an administrator.`,
// 		503: "The server is currently down for maintenance and should be back soon. =)",
// 	}
// 	msg, exists := messages[error.StatusCode]
// 	if !exists {
// 		return nil, errors.New("No valid message for the given code")
// 	}
// 	return page.Error(error.StatusCode, http.StatusText(error.StatusCode), msg), nil
// }

func ErrorPage(hwsError hws.HWSError) (hws.ErrorPage, error) {
	// Determine if this status code should show technical details
	showDetails := shouldShowDetails(hwsError.StatusCode)

	// Get the user-friendly message
	message := hwsError.Message
	if message == "" {
		// Fallback to default messages if no custom message provided
		message = getDefaultMessage(hwsError.StatusCode)
	}

	// Get technical details if applicable
	var details string
	if showDetails && hwsError.Error != nil {
		details = hwsError.Error.Error()
	}

	// Render appropriate template
	if details != "" {
		return page.ErrorWithDetails(
			hwsError.StatusCode,
			http.StatusText(hwsError.StatusCode),
			message,
			details,
		), nil
	}

	return page.Error(
		hwsError.StatusCode,
		http.StatusText(hwsError.StatusCode),
		message,
	), nil
}

// shouldShowDetails determines if a status code should display technical details
func shouldShowDetails(statusCode int) bool {
	switch statusCode {
	case 400, 500, 503: // Bad Request, Internal Server Error, Service Unavailable
		return true
	case 401, 403, 404: // Unauthorized, Forbidden, Not Found
		return false
	default:
		// For unknown codes, show details for 5xx errors
		return statusCode >= 500
	}
}

// getDefaultMessage provides fallback messages for status codes
func getDefaultMessage(statusCode int) string {
	messages := map[int]string{
		400: "The request you made was malformed or unexpected.",
		401: "You need to login to view this page.",
		403: "You do not have permission to view this page.",
		404: "The page or resource you have requested does not exist.",
		500: `An error occurred on the server. Please try again, and if this
            continues to happen contact an administrator.`,
		503: "The server is currently down for maintenance and should be back soon. =)",
	}

	msg, exists := messages[statusCode]
	if !exists {
		if statusCode >= 500 {
			return "A server error occurred. Please try again later."
		}
		return "An error occurred while processing your request."
	}

	return msg
}
