package handler

import (
	"encoding/json"
	"net/http"

	"freeleaps.com/gitea-webhook-ambassador/internal/auth"
	"freeleaps.com/gitea-webhook-ambassador/internal/config"
	"freeleaps.com/gitea-webhook-ambassador/internal/worker"
)

// HealthHandler handles health check requests
type HealthHandler struct {
	workerPool *worker.Pool
	config     *config.Configuration
	auth       *auth.Middleware
}

// NewHealthHandler creates a new health check handler
func NewHealthHandler(workerPool *worker.Pool, config *config.Configuration) *HealthHandler {
	return &HealthHandler{
		workerPool: workerPool,
		config:     config,
		auth:       auth.NewMiddleware(config.Server.SecretKey),
	}
}

// HealthResponse represents the health check response
type HealthResponse struct {
	Status  string `json:"status"`
	Jenkins struct {
		Status  string `json:"status"`
		Message string `json:"message,omitempty"`
	} `json:"jenkins"`
	WorkerPool struct {
		ActiveWorkers int `json:"active_workers"`
		QueueSize     int `json:"queue_size"`
	} `json:"worker_pool"`
}

// verifyAuth verifies the JWT token in the request
func (h *HealthHandler) verifyAuth(r *http.Request) error {
	return h.auth.VerifyToken(r)
}

// HandleHealth handles health check requests
func (h *HealthHandler) HandleHealth(w http.ResponseWriter, r *http.Request) {
	// Verify JWT token
	if err := h.verifyAuth(r); err != nil {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	response := HealthResponse{}

	// Check Jenkins connection
	if h.workerPool.IsJenkinsConnected() {
		response.Jenkins.Status = "connected"
	} else {
		response.Jenkins.Status = "disconnected"
		response.Jenkins.Message = "Unable to connect to Jenkins server"
	}

	// Get worker pool stats
	stats := h.workerPool.GetStats()
	response.WorkerPool.ActiveWorkers = stats.ActiveWorkers
	response.WorkerPool.QueueSize = stats.QueueSize

	// Set overall status
	if response.Jenkins.Status == "connected" {
		response.Status = "healthy"
	} else {
		response.Status = "unhealthy"
	}

	// Set response headers
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	// Write response
	if err := json.NewEncoder(w).Encode(response); err != nil {
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
		return
	}
}
