// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"strings"
	"time"

	"go.mau.fi/whatsmeow"
	waProto "go.mau.fi/whatsmeow/proto/waE2E"
	"go.mau.fi/whatsmeow/types"
	"google.golang.org/protobuf/proto"
)

func replyButtonsMessage(body, footer string, buttons []ReplyButton) (*waProto.Message, error) {
	if len(buttons) < 1 || len(buttons) > 3 {
		return nil, fmt.Errorf("gunakan 1–3 tombol")
	}
	items := make([]*waProto.InteractiveMessage_NativeFlowMessage_NativeFlowButton, 0, len(buttons))
	ids := make(map[string]bool, len(buttons))
	for _, button := range buttons {
		id, label := strings.TrimSpace(button.ID), strings.TrimSpace(button.Text)
		if id == "" || ids[id] || label == "" {
			return nil, fmt.Errorf("ID tombol harus unik dan nama tombol wajib diisi")
		}
		ids[id] = true
		params, err := json.Marshal(map[string]string{"display_text": label, "id": id})
		if err != nil {
			return nil, err
		}
		items = append(items, &waProto.InteractiveMessage_NativeFlowMessage_NativeFlowButton{
			Name: proto.String("quick_reply"), ButtonParamsJSON: proto.String(string(params)),
		})
	}
	return &waProto.Message{InteractiveMessage: &waProto.InteractiveMessage{
		Header: &waProto.InteractiveMessage_Header{HasMediaAttachment: proto.Bool(false)},
		Body:   &waProto.InteractiveMessage_Body{Text: proto.String(body)},
		Footer: &waProto.InteractiveMessage_Footer{Text: proto.String(footer)},
		InteractiveMessage: &waProto.InteractiveMessage_NativeFlowMessage_{
			NativeFlowMessage: &waProto.InteractiveMessage_NativeFlowMessage{MessageVersion: proto.Int32(3), Buttons: items},
		},
	}}, nil
}

func (w *waInstance) SendButtons(to, body, footer string, buttons []ReplyButton) error {
	_, err := w.sendButtonsWithDelayAndGetID(to, body, footer, buttons, 0, 0, false, nil)
	return err
}

func (w *waInstance) SendButtonsWithDelay(to, body, footer string, buttons []ReplyButton, minSeconds, maxSeconds int) error {
	_, err := w.SendButtonsWithDelayAndGetID(to, body, footer, buttons, minSeconds, maxSeconds, nil)
	return err
}

// Preserve the WhatsApp ID and automatic origin, just like text/image replies.
// Operator takeover is checked again after typing and before network delivery.
func (w *waInstance) SendButtonsWithDelayAndGetID(toNumber, body, footer string, buttons []ReplyButton, minSeconds, maxSeconds int, beforeSend func() error) (string, error) {
	return w.sendButtonsWithDelayAndGetID(toNumber, body, footer, buttons, minSeconds, maxSeconds, true, beforeSend)
}

func (w *waInstance) sendButtonsWithDelayAndGetID(toNumber, body, footer string, buttons []ReplyButton, minSeconds, maxSeconds int, automatic bool, beforeSend func() error) (string, error) {
	if beforeSend != nil {
		if err := beforeSend(); err != nil {
			return "", err
		}
	}
	if automatic && !AutomaticRecipientAllowed(toNumber) {
		return "", fmt.Errorf("penerima berada di luar cakupan uji balasan otomatis")
	}
	msg, err := replyButtonsMessage(body, footer, buttons)
	if err != nil {
		return "", err
	}
	to, err := recipientJID(toNumber)
	if err != nil {
		return "", err
	}
	w.mu.Lock()
	client := w.client
	w.mu.Unlock()
	if client == nil || !client.IsConnected() {
		return "", fmt.Errorf("client WA tidak terhubung")
	}
	minSeconds = max(0, min(30, minSeconds))
	maxSeconds = max(minSeconds, min(30, maxSeconds))
	delay := minSeconds
	if maxSeconds > minSeconds {
		delay += rand.Intn(maxSeconds - minSeconds + 1)
	}
	ctx, cancel := context.WithTimeout(context.Background(), interactiveWASendTimeout+time.Duration(delay)*time.Second)
	defer cancel()
	_ = client.SendPresence(ctx, types.PresenceAvailable)
	if delay > 0 {
		_ = client.SendChatPresence(ctx, to, types.ChatPresenceComposing, types.ChatPresenceMediaText)
		err = waitWASendDelay(ctx, time.Duration(delay)*time.Second)
		_ = client.SendChatPresence(ctx, to, types.ChatPresencePaused, types.ChatPresenceMediaText)
		if err != nil {
			return "", err
		}
	}
	if beforeSend != nil {
		if err := beforeSend(); err != nil {
			return "", err
		}
	}
	id := client.GenerateMessageID()
	if automatic {
		rememberAutomaticReply(w.agentID, id)
	}
	nodes := nativeFlowBizNodes()
	resp, err := client.SendMessage(ctx, to, msg, whatsmeow.SendRequestExtra{ID: id, AdditionalNodes: &nodes})
	if err != nil {
		return id, normalizeWASendError(err, interactiveWASendTimeout)
	}
	return resp.ID, nil
}

// Keep incoming native menus visible in Inbox/history. These are message
// contents, not a customer's click: never manufacture an ActionID from them.
func interactiveMenuText(m *waProto.Message) (string, string, bool) {
	menu := m.GetInteractiveMessage()
	if menu == nil {
		return "", "", false
	}
	var lines []string
	if body := strings.TrimSpace(menu.GetBody().GetText()); body != "" {
		lines = append(lines, body)
	}
	for _, button := range menu.GetNativeFlowMessage().GetButtons() {
		var params struct {
			DisplayText string `json:"display_text"`
		}
		if json.Unmarshal([]byte(button.GetButtonParamsJSON()), &params) == nil && strings.TrimSpace(params.DisplayText) != "" {
			lines = append(lines, "• "+strings.TrimSpace(params.DisplayText))
		}
	}
	if footer := strings.TrimSpace(menu.GetFooter().GetText()); footer != "" {
		lines = append(lines, footer)
	}
	return strings.Join(lines, "\n"), contextReplyID(menu.GetContextInfo()), len(lines) > 0
}
