package handlers

import (
	"fmt"
	"io"
	"net/http"
	"strings"

	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/proxy"
	"github.com/go-chi/chi/v5"
	"go.uber.org/zap"
)

// DicomHandler handles DICOM Web requests
type DicomHandler struct {
	client *proxy.Client
	logger *zap.Logger
}

// NewDicomHandler creates a new DICOM handler
func NewDicomHandler(client *proxy.Client, logger *zap.Logger) *DicomHandler {
	return &DicomHandler{
		client: client,
		logger: logger,
	}
}

// ForwardRequest forwards the request to Google Healthcare API
func (h *DicomHandler) ForwardRequest(w http.ResponseWriter, r *http.Request) {
	// Get the path after /dicomWeb
	urlPath := chi.URLParam(r, "*")

	// If the URL parameter is empty, try to extract it from the URL path
	if urlPath == "" {
		// Remove /dicomWeb prefix from the URL
		prefix := "/dicomWeb"
		if strings.HasPrefix(r.URL.Path, prefix) {
			urlPath = r.URL.Path[len(prefix):]
		}
	}

	h.logger.Debug("Forwarding request",
		zap.String("path", urlPath),
		zap.String("method", r.Method),
		zap.String("url", r.URL.String()),
	)

	// Read request body if present
	var bodyBytes []byte
	if r.Body != nil && r.ContentLength > 0 {
		var err error
		bodyBytes, err = io.ReadAll(r.Body)
		if err != nil {
			h.logger.Error("Failed to read request body", zap.Error(err))
			http.Error(w, "Failed to read request body", http.StatusInternalServerError)
			return
		}
	}

	// Copy query parameters
	queryParams := r.URL.Query().Encode()
	if queryParams != "" {
		if !strings.HasPrefix(urlPath, "/") {
			urlPath = "/" + urlPath
		}
		urlPath = urlPath + "?" + queryParams
	}

	// Get request headers
	headers := make(map[string]string)
	for k, v := range r.Header {
		if len(v) > 0 {
			headers[k] = v[0]
		}
	}

	// Forward the request to Healthcare API
	response, err := h.client.ForwardRequest(
		r.Context(),
		r.Method,
		urlPath,
		headers,
		bodyBytes,
	)

	if err != nil {
		h.logger.Error("Request forwarding failed", zap.Error(err))
		http.Error(w, fmt.Sprintf("Request failed: %v", err), http.StatusInternalServerError)
		return
	}

	// Set response headers
	for k, v := range response.Headers {
		w.Header().Set(k, v)
	}

	// Set status and write response body
	w.WriteHeader(response.StatusCode)
	w.Write(response.Body)
}
