package handler

import (
	"log/slog"
	"net/http"
	"strings"

	"mkiso-server/internal/service"
)

// PrintISO handles GET /api/iso/print?accession_number=X
// This single endpoint handles both single and multi-accession relay.
// If accession_number contains commas, it auto-detects multi mode.
// Returns JSON response with relay results.
func PrintISO(relaySvc *service.RelayService) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		acc := r.URL.Query().Get("accession_number")
		if acc == "" {
			writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing accession_number"})
			return
		}

		accs := parseAccessions(acc)
		if len(accs) == 0 {
			writeJSON(w, http.StatusBadRequest, map[string]string{"error": "empty accession_number"})
			return
		}

		slog.Info("handling print/relay",
			"accessions", accs,
			"mode", map[bool]string{true: "multi", false: "single"}[len(accs) > 1],
		)

		result, err := relaySvc.RelayToCDPublisher(r.Context(), accs)
		if err != nil {
			slog.Error("print ISO relay failed", "accessions", accs, "error", err)
			status := http.StatusBadGateway
			msg := "DICOM relay failed"

			if strings.Contains(err.Error(), "no DICOM data") {
				status = http.StatusNotFound
				msg = "no DICOM data for accession_number"
			} else if strings.Contains(err.Error(), "storescu relay failed") {
				msg = "CD Publisher unreachable"
			}

			writeJSON(w, status, map[string]string{
				"error":       msg,
				"detail":      err.Error(),
				"destination": relaySvc.Destination(),
			})
			return
		}

		writeJSON(w, http.StatusOK, map[string]interface{}{
			"status":          "ok",
			"accessions_sent": result.AccessionsSent,
			"patient_name":    result.PatientName,
			"destination":     result.Destination,
			"files_sent":      result.FilesSent,
		})
	}
}
