package handlers

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

	"git.warky.dev/wdevs/whatshooked/pkg/utils"
	"go.mau.fi/whatsmeow/types"
)

// SendMessage sends a text message via WhatsApp
func (h *Handlers) SendMessage(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"`
		To        string `json:"to"`
		Text      string `json:"text"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Format phone number to JID format
	formattedJID := utils.FormatPhoneToJID(req.To, h.config.Server.DefaultCountryCode)

	jid, err := types.ParseJID(formattedJID)
	if err != nil {
		http.Error(w, "Invalid JID", http.StatusBadRequest)
		return
	}

	if err := h.whatsappMgr.SendTextMessage(r.Context(), req.AccountID, jid, req.Text); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	writeJSON(w, map[string]string{"status": "ok"})
}

// SendImage sends an image via WhatsApp
func (h *Handlers) SendImage(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"`
		To        string `json:"to"`
		Caption   string `json:"caption"`
		MimeType  string `json:"mime_type"`
		ImageData string `json:"image_data"` // base64 encoded
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Decode base64 image data
	imageData, err := base64.StdEncoding.DecodeString(req.ImageData)
	if err != nil {
		http.Error(w, "Invalid base64 image data", http.StatusBadRequest)
		return
	}

	// Format phone number to JID format
	formattedJID := utils.FormatPhoneToJID(req.To, h.config.Server.DefaultCountryCode)
	jid, err := types.ParseJID(formattedJID)
	if err != nil {
		http.Error(w, "Invalid JID", http.StatusBadRequest)
		return
	}

	// Default mime type if not provided
	if req.MimeType == "" {
		req.MimeType = "image/jpeg"
	}

	if err := h.whatsappMgr.SendImage(r.Context(), req.AccountID, jid, imageData, req.MimeType, req.Caption); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	writeJSON(w, map[string]string{"status": "ok"})
}

// SendVideo sends a video via WhatsApp
func (h *Handlers) SendVideo(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"`
		To        string `json:"to"`
		Caption   string `json:"caption"`
		MimeType  string `json:"mime_type"`
		VideoData string `json:"video_data"` // base64 encoded
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Decode base64 video data
	videoData, err := base64.StdEncoding.DecodeString(req.VideoData)
	if err != nil {
		http.Error(w, "Invalid base64 video data", http.StatusBadRequest)
		return
	}

	// Format phone number to JID format
	formattedJID := utils.FormatPhoneToJID(req.To, h.config.Server.DefaultCountryCode)
	jid, err := types.ParseJID(formattedJID)
	if err != nil {
		http.Error(w, "Invalid JID", http.StatusBadRequest)
		return
	}

	// Default mime type if not provided
	if req.MimeType == "" {
		req.MimeType = "video/mp4"
	}

	if err := h.whatsappMgr.SendVideo(r.Context(), req.AccountID, jid, videoData, req.MimeType, req.Caption); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	writeJSON(w, map[string]string{"status": "ok"})
}

// SendDocument sends a document via WhatsApp
func (h *Handlers) SendDocument(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"`
		To           string `json:"to"`
		Caption      string `json:"caption"`
		MimeType     string `json:"mime_type"`
		Filename     string `json:"filename"`
		DocumentData string `json:"document_data"` // base64 encoded
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Decode base64 document data
	documentData, err := base64.StdEncoding.DecodeString(req.DocumentData)
	if err != nil {
		http.Error(w, "Invalid base64 document data", http.StatusBadRequest)
		return
	}

	// Format phone number to JID format
	formattedJID := utils.FormatPhoneToJID(req.To, h.config.Server.DefaultCountryCode)
	jid, err := types.ParseJID(formattedJID)
	if err != nil {
		http.Error(w, "Invalid JID", http.StatusBadRequest)
		return
	}

	// Default values if not provided
	if req.MimeType == "" {
		req.MimeType = "application/octet-stream"
	}
	if req.Filename == "" {
		req.Filename = "document"
	}

	if err := h.whatsappMgr.SendDocument(r.Context(), req.AccountID, jid, documentData, req.MimeType, req.Filename, req.Caption); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	writeJSON(w, map[string]string{"status": "ok"})
}
