// Package handlers provides HTTP handlers for the rdev API.
package handlers

import (
	"context"
	"net/http"

	"github.com/go-chi/chi/v5"

	"github.com/orchard9/rdev/internal/auth"
	"github.com/orchard9/rdev/internal/domain"
	"github.com/orchard9/rdev/internal/logging"
	"github.com/orchard9/rdev/internal/port"
	"github.com/orchard9/rdev/pkg/api"
)

// DiagnosticsGetter retrieves project diagnostics.
type DiagnosticsGetter interface {
	GetDiagnostics(ctx context.Context, projectID string) (*domain.ProjectDiagnostics, error)
}

// DiagnosticsHandler handles project diagnostics requests.
type DiagnosticsHandler struct {
	diagnostics DiagnosticsGetter
	projects    port.ProjectRepository
}

// NewDiagnosticsHandler creates a new diagnostics handler.
func NewDiagnosticsHandler(
	diagnostics DiagnosticsGetter,
	projects port.ProjectRepository,
) *DiagnosticsHandler {
	return &DiagnosticsHandler{
		diagnostics: diagnostics,
		projects:    projects,
	}
}

// Mount registers the diagnostics routes.
func (h *DiagnosticsHandler) Mount(r api.Router) {
	r.Route("/projects/{projectId}/diagnostics", func(r chi.Router) {
		r.With(auth.RequireScope(auth.ScopeProjectsRead, auth.ScopeAdmin)).Get("/", h.GetDiagnostics)
	})
}

// GetDiagnostics returns comprehensive health information for a project.
// GET /projects/{projectId}/diagnostics
func (h *DiagnosticsHandler) GetDiagnostics(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), TimeoutStandard)
	defer cancel()

	projectID := chi.URLParam(r, "projectId")
	if projectID == "" {
		api.WriteBadRequest(w, r, "project ID is required")
		return
	}

	log := logging.FromContext(ctx).WithHandler("GetDiagnostics")

	// Verify project exists (optional - diagnostics can still be useful for non-k8s projects)
	if h.projects != nil {
		if _, err := h.projects.Get(ctx, domain.ProjectID(projectID)); err != nil {
			if err == domain.ErrProjectNotFound {
				// Log but continue - the project might exist in git/CI but not as a k8s pod
				log.Debug("project not found in k8s, continuing with diagnostics",
					logging.FieldProjectID, projectID,
				)
			}
		}
	}

	diag, err := h.diagnostics.GetDiagnostics(ctx, projectID)
	if err != nil {
		log.Error("failed to get diagnostics",
			logging.FieldError, err.Error(),
			logging.FieldProjectID, projectID,
		)
		api.WriteInternalError(w, r, "failed to retrieve diagnostics")
		return
	}

	api.WriteSuccess(w, r, diag)
}
