package api

import (
	"net/http"
	"time"

	"github.com/ez-api/ez-api/internal/service"
	"github.com/gin-gonic/gin"
)

// Version is set at build time using ldflags
// e.g., go build -ldflags "-X github.com/ez-api/ez-api/internal/api.Version=v1.0.0"
var Version = "v0.1.0-dev"

// startTime is used to calculate uptime
var startTime = time.Now()

// StatusHandler handles public status endpoints
type StatusHandler struct {
	healthService *service.HealthCheckService
}

// NewStatusHandler creates a new StatusHandler
func NewStatusHandler(healthService *service.HealthCheckService) *StatusHandler {
	return &StatusHandler{
		healthService: healthService,
	}
}

// StatusResponse represents the response for /status endpoint
type StatusResponse struct {
	Status  string `json:"status" example:"ok"`
	Uptime  string `json:"uptime" example:"72h30m15s"`
	Version string `json:"version" example:"0.1.0"`
}

// AboutResponse represents the response for /about endpoint
type AboutResponse struct {
	Name        string `json:"name" example:"EZ-API Gateway"`
	Version     string `json:"version" example:"0.1.0"`
	Description string `json:"description" example:"High-performance LLM API gateway"`
	Repository  string `json:"repository" example:"https://github.com/ez-api/ez-api"`
}

// Status godoc
// @Summary      Get system status
// @Description  Returns public runtime status information without sensitive data
// @Tags         Public
// @Produce      json
// @Success      200  {object}  StatusResponse
// @Router       /status [get]
func (h *StatusHandler) Status(c *gin.Context) {
	// Check health status
	health := h.healthService.Check(c.Request.Context())

	resp := StatusResponse{
		Status:  health.Status,
		Uptime:  time.Since(startTime).Round(time.Second).String(),
		Version: Version,
	}

	c.JSON(http.StatusOK, resp)
}

// About godoc
// @Summary      Get system information
// @Description  Returns system metadata for display on an about page
// @Tags         Public
// @Produce      json
// @Success      200  {object}  AboutResponse
// @Router       /about [get]
func (h *StatusHandler) About(c *gin.Context) {
	resp := AboutResponse{
		Name:        "EZ-API Gateway",
		Version:     Version,
		Description: "High-performance LLM API gateway",
		Repository:  "https://github.com/ez-api/ez-api",
	}

	c.JSON(http.StatusOK, resp)
}
