// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"fmt"
	"strings"

	"go.mau.fi/whatsmeow/proto/waE2E"
	"go.mau.fi/whatsmeow/types"
	"google.golang.org/protobuf/proto"
	"wa-assistant/backend/models"
)

// IsOutgoingHistoryMessage excludes legacy rows combining an incoming stanza
// and a generated reply: their WAMsgID still identifies the incoming message.
func IsOutgoingHistoryMessage(row models.ChatHistory) bool {
	return row.MediaType != "call" && row.MediaType != "system" && strings.TrimSpace(row.Message) == "" && (strings.TrimSpace(row.Reply) != "" || row.FromHuman)
}

func buildInboxQuoteContext(row models.ChatHistory, chat, own types.JID) (*waE2E.ContextInfo, error) {
	if strings.TrimSpace(row.WAMsgID) == "" || row.Revoked || row.MediaType == "call" || row.MediaType == "system" {
		return nil, fmt.Errorf("pesan yang dibalas tidak tersedia")
	}
	participant := chat.ToNonAD()
	text := row.Message
	if IsOutgoingHistoryMessage(row) {
		if own.IsEmpty() {
			return nil, fmt.Errorf("akun WhatsApp belum login")
		}
		participant = own.ToNonAD()
		text = row.Reply
	} else if row.ParticipantJID != "" {
		parsed, err := types.ParseJID(row.ParticipantJID)
		if err != nil || parsed.IsEmpty() || (parsed.Server != types.DefaultUserServer && parsed.Server != types.HiddenUserServer) {
			return nil, fmt.Errorf("identitas pengirim kutipan tidak valid; sinkronkan riwayat")
		}
		participant = parsed.ToNonAD()
	} else if chat.Server == types.GroupServer {
		return nil, fmt.Errorf("identitas pengirim pesan grup belum tersedia; sinkronkan riwayat sebelum membalas")
	}
	quoted := &waE2E.Message{Conversation: proto.String(text)}
	if len(row.MediaMetadata) > 0 {
		// Only copy the quoted content. ContextInfo can recursively contain older
		// quotes and must not be recursively retransmitted.
		var media waE2E.Message
		if proto.Unmarshal(row.MediaMetadata, &media) == nil {
			switch {
			case media.ImageMessage != nil:
				media.ImageMessage.ContextInfo = nil
				quoted = &waE2E.Message{ImageMessage: media.ImageMessage}
			case media.VideoMessage != nil:
				media.VideoMessage.ContextInfo = nil
				quoted = &waE2E.Message{VideoMessage: media.VideoMessage}
			case media.AudioMessage != nil:
				media.AudioMessage.ContextInfo = nil
				quoted = &waE2E.Message{AudioMessage: media.AudioMessage}
			case media.DocumentMessage != nil:
				media.DocumentMessage.ContextInfo = nil
				quoted = &waE2E.Message{DocumentMessage: media.DocumentMessage}
			case media.StickerMessage != nil:
				media.StickerMessage.ContextInfo = nil
				quoted = &waE2E.Message{StickerMessage: media.StickerMessage}
			}
		}
	}
	return &waE2E.ContextInfo{StanzaID: proto.String(row.WAMsgID), Participant: proto.String(participant.String()), QuotedMessage: quoted}, nil
}

func (w *waInstance) InboxQuoteContext(to string, row models.ChatHistory) (*waE2E.ContextInfo, error) {
	if row.AgentID != w.agentID || NormalizeInboxSender(row.Sender) != NormalizeInboxSender(to) {
		return nil, fmt.Errorf("pesan yang dibalas bukan bagian dari percakapan ini")
	}
	jid, err := recipientJID(to)
	if err != nil {
		return nil, err
	}
	w.mu.Lock()
	client := w.client
	w.mu.Unlock()
	if client == nil || client.Store.ID == nil {
		return nil, fmt.Errorf("akun WhatsApp belum login")
	}
	return buildInboxQuoteContext(row, jid, *client.Store.ID)
}

func (w *waInstance) SendImmediateQuotedMessageAndGetID(to, text string, quote *waE2E.ContextInfo) (string, error) {
	w.mu.Lock()
	client := w.client
	w.mu.Unlock()
	if client == nil || !client.IsConnected() {
		return "", fmt.Errorf("client WA tidak terhubung")
	}
	jid, err := recipientJID(to)
	if err != nil {
		return "", err
	}
	ctx, cancel := context.WithTimeout(context.Background(), interactiveWASendTimeout)
	defer cancel()
	result, err := client.SendMessage(ctx, jid, &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{Text: proto.String(text), ContextInfo: quote}})
	if err != nil {
		return "", normalizeWASendError(err, interactiveWASendTimeout)
	}
	return result.ID, nil
}

func firstMediaQuote(quotes []*waE2E.ContextInfo) *waE2E.ContextInfo {
	if len(quotes) == 0 {
		return nil
	}
	return quotes[0]
}
