package handlers

import (
	"encoding/base64"
	"encoding/json"
	"net/http"
)

// UploadMedia uploads a media file to Meta's servers and returns the media ID.
// Useful for pre-uploading media before referencing the ID in a subsequent send call.
// POST /api/media/upload  {"account_id","data"(base64),"mime_type"}
func (h *Handlers) UploadMedia(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req struct {
		AccountID string `json:"account_id"`
		Data      string `json:"data"`
		MimeType  string `json:"mime_type"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if req.Data == "" || req.MimeType == "" {
		http.Error(w, "data and mime_type are required", http.StatusBadRequest)
		return
	}

	baClient, err := h.getBusinessAPIClient(req.AccountID)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	mediaData, err := base64.StdEncoding.DecodeString(req.Data)
	if err != nil {
		http.Error(w, "Invalid base64 data", http.StatusBadRequest)
		return
	}

	mediaID, err := baClient.UploadMedia(r.Context(), mediaData, req.MimeType)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	writeJSON(w, map[string]string{"media_id": mediaID})
}
