package httpserver

import (
	"net/http"
	"net/url"
	"strconv"

	apicontract "bit.admedia.com/scm/ad/adpilot-indexing-repo-sync.com/internal/contracts/api"
)

func handleGetLatestIndexingRun(reader MetadataReader) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		repoID, err := parseRepoID(r)
		if err != nil {
			writeJSON(w, http.StatusBadRequest, errorResponse{Error: err.Error()})
			return
		}

		run, ok := reader.GetLatestIndexingRun(repoID)
		if !ok {
			writeJSON(w, http.StatusNotFound, errorResponse{Error: "indexing run not found"})
			return
		}

		writeJSON(w, http.StatusOK, apicontract.IndexingRunFromDomain(run))
	}
}

func handleGetIndexingRunBySnapshot(reader MetadataReader) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		repoID, err := parseRepoID(r)
		if err != nil {
			writeJSON(w, http.StatusBadRequest, errorResponse{Error: err.Error()})
			return
		}

		snapshotID, err := url.PathUnescape(r.PathValue("snapshot_id"))
		if err != nil || snapshotID == "" {
			writeJSON(w, http.StatusBadRequest, errorResponse{Error: "invalid snapshot_id path"})
			return
		}

		run, ok := reader.GetIndexingRunBySnapshot(repoID, snapshotID)
		if !ok {
			writeJSON(w, http.StatusNotFound, errorResponse{Error: "indexing run not found"})
			return
		}

		writeJSON(w, http.StatusOK, apicontract.IndexingRunFromDomain(run))
	}
}

func handleGetIndexingDiagnostics(reader MetadataReader) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		repoID, err := parseRepoID(r)
		if err != nil {
			writeJSON(w, http.StatusBadRequest, errorResponse{Error: err.Error()})
			return
		}

		snapshotID, err := url.PathUnescape(r.PathValue("snapshot_id"))
		if err != nil || snapshotID == "" {
			writeJSON(w, http.StatusBadRequest, errorResponse{Error: "invalid snapshot_id path"})
			return
		}

		limit := 100
		if raw := r.URL.Query().Get("limit"); raw != "" {
			value, parseErr := strconv.Atoi(raw)
			if parseErr != nil || value < 1 {
				writeJSON(w, http.StatusBadRequest, errorResponse{Error: "invalid limit query"})
				return
			}
			limit = value
		}

		diagnostics, ok := reader.ListIndexingDiagnostics(repoID, snapshotID, limit)
		if !ok {
			writeJSON(w, http.StatusNotFound, errorResponse{Error: "indexing diagnostics not found"})
			return
		}

		writeJSON(w, http.StatusOK, apicontract.IndexingDiagnosticsFromDomain(diagnostics))
	}
}
