package handlers

import (
	"net/http"

	"git.warky.dev/wdevs/whatshooked/pkg/logging"
	"git.warky.dev/wdevs/whatshooked/pkg/whatsapp/whatsmeow"
)

// ServeQRCode serves the QR code image for a WhatsApp account
func (h *Handlers) ServeQRCode(w http.ResponseWriter, r *http.Request) {
	// Expected path format: /api/qr/{accountID}
	path := r.URL.Path[len("/api/qr/"):]
	accountID := path

	if accountID == "" {
		http.Error(w, "Invalid QR code path", http.StatusBadRequest)
		return
	}

	// Get client from manager
	client, exists := h.whatsappMgr.GetClient(accountID)
	if !exists {
		http.Error(w, "Account not found", http.StatusNotFound)
		return
	}

	// Type assert to whatsmeow client (only whatsmeow clients have QR codes)
	whatsmeowClient, ok := client.(*whatsmeow.Client)
	if !ok {
		http.Error(w, "QR codes are only available for whatsmeow clients", http.StatusBadRequest)
		logging.Warn("QR code requested for non-whatsmeow client", "account_id", accountID)
		return
	}

	// Get QR code PNG
	pngData, err := whatsmeowClient.GetQRCodePNG()
	if err != nil {
		if err.Error() == "no QR code available" {
			http.Error(w, "No QR code available. The account may already be connected or pairing has not started yet.", http.StatusNotFound)
		} else {
			logging.Error("Failed to generate QR code PNG", "account_id", accountID, "error", err)
			http.Error(w, "Failed to generate QR code", http.StatusInternalServerError)
		}
		return
	}

	// Set headers
	w.Header().Set("Content-Type", "image/png")
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")

	// Write PNG data
	writeBytes(w, pngData)
	logging.Debug("QR code served", "account_id", accountID)
}
