package services

import (
	"go.mau.fi/whatsmeow"
	"go.mau.fi/whatsmeow/proto/waCommon"
	"go.mau.fi/whatsmeow/proto/waE2E"
	"go.mau.fi/whatsmeow/proto/waHistorySync"
	"go.mau.fi/whatsmeow/proto/waSyncAction"
	"go.mau.fi/whatsmeow/proto/waWeb"
	"go.mau.fi/whatsmeow/types"
	"go.mau.fi/whatsmeow/types/events"
	"google.golang.org/protobuf/proto"
	"testing"
	"time"
)

func TestHistorySyncPreservesMissedCallStub(t *testing.T) {
	previous, previousStates := onHistorySync, onHistoryChatState
	t.Cleanup(func() { onHistorySync = previous; onHistoryChatState = previousStates })
	onHistoryChatState = nil
	var captured []HistoricalMessage
	onHistorySync = func(_ uint, msgs []HistoricalMessage) (int, int, error) {
		captured = append(captured, msgs...)
		return len(msgs), 0, nil
	}
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}, historyWaiters: make(map[string][]chan struct{})}
	jid := "628111111111@s.whatsapp.net"
	w.processHistorySync(&events.HistorySync{Data: &waHistorySync.HistorySync{SyncType: waHistorySync.HistorySync_RECENT.Enum(), Progress: proto.Uint32(100), Conversations: []*waHistorySync.Conversation{{ID: &jid, Messages: []*waHistorySync.HistorySyncMsg{{Message: &waWeb.WebMessageInfo{Key: &waCommon.MessageKey{ID: proto.String("call-stub-1"), RemoteJID: &jid, FromMe: proto.Bool(false)}, MessageTimestamp: proto.Uint64(1788772200), MessageStubType: waWeb.WebMessageInfo_CALL_MISSED_VIDEO.Enum()}}}}}}})
	if len(captured) != 1 {
		t.Fatalf("Log panggilan terlewat hilang: mendapat %d baris, ingin 1", len(captured))
	}
	if captured[0].Sender != "628111111111" || captured[0].MediaType != "call" || captured[0].Text != "" {
		t.Fatalf("log harus terpisah dari isi pesan pelanggan: %+v", captured[0])
	}
}

func TestLiveCallLogUsesHistoryOnly(t *testing.T) {
	previous, previousMessage := onHistorySync, onMessage
	t.Cleanup(func() { onHistorySync = previous; onMessage = previousMessage })
	var captured []HistoricalMessage
	onHistorySync = func(_ uint, msgs []HistoricalMessage) (int, int, error) {
		captured = append(captured, msgs...)
		return len(msgs), 0, nil
	}
	onMessage = func(_ uint, _ types.JID, _ IncomingMessage) { t.Error("Call log memicu chatbot") }
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	jid := types.NewJID("628111111111", types.DefaultUserServer)
	w.handleEvent(&events.Message{Info: types.MessageInfo{MessageSource: types.MessageSource{Chat: jid, Sender: jid}, ID: "call-log-1", Timestamp: time.Unix(1788772200, 0)}, Message: &waE2E.Message{CallLogMesssage: &waE2E.CallLogMessage{IsVideo: proto.Bool(true), CallOutcome: waE2E.CallLogMessage_CONNECTED.Enum(), DurationSecs: proto.Int64(125)}}})
	if len(captured) != 1 || captured[0].Call == nil || captured[0].Call.DurationSeconds == nil || *captured[0].Call.DurationSeconds != 125 {
		t.Fatalf("Call log live tidak diteruskan dengan durasi protokol: %+v", captured)
	}
	if len(captured) == 1 && captured[0].WAMsgID != callHistoryID("628111111111", "call-log-1") {
		t.Fatal("live call dan history memakai identitas berbeda untuk panggilan yang sama")
	}
}

func TestCallRecordSyncRoutesIncomingAndOutgoing(t *testing.T) {
	previous := onHistorySync
	t.Cleanup(func() { onHistorySync = previous })
	var captured []HistoricalMessage
	onHistorySync = func(_ uint, msgs []HistoricalMessage) (int, int, error) {
		captured = append(captured, msgs...)
		return len(msgs), 0, nil
	}
	record := &waSyncAction.CallLogRecord{CallID: proto.String("record-1"), CallCreatorJID: proto.String("628111111111@s.whatsapp.net"), IsIncoming: proto.Bool(true), IsVideo: proto.Bool(false), CallResult: waSyncAction.CallLogRecord_MISSED.Enum(), StartTime: proto.Int64(1788772200)}
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}, historyWaiters: make(map[string][]chan struct{})}
	w.processHistorySync(&events.HistorySync{Data: &waHistorySync.HistorySync{SyncType: waHistorySync.HistorySync_RECENT.Enum(), Progress: proto.Uint32(100), CallLogRecords: []*waSyncAction.CallLogRecord{record}}})
	outgoing := proto.Clone(record).(*waSyncAction.CallLogRecord)
	outgoing.CallID = proto.String("record-2")
	outgoing.IsIncoming = proto.Bool(false)
	outgoing.CallCreatorJID = proto.String("628999999999@s.whatsapp.net")
	outgoing.Participants = []*waSyncAction.CallLogRecord_ParticipantInfo{{UserJID: proto.String("628999999999@s.whatsapp.net")}, {UserJID: proto.String("628111111111@s.whatsapp.net")}}
	outgoing.CallResult = waSyncAction.CallLogRecord_CONNECTED.Enum()
	w.handleEvent(&events.AppState{SyncActionValue: &waSyncAction.SyncActionValue{CallLogAction: &waSyncAction.CallLogAction{CallLogRecord: outgoing}}})
	if len(captured) != 2 {
		t.Fatalf("call record history/appstate hilang: %d", len(captured))
	}
	for _, msg := range captured {
		if msg.Sender != "628111111111" {
			t.Fatalf("call dipasang ke chat yang salah: %+v", msg)
		}
	}
	if captured[0].Call.Status != "missed" || !captured[1].FromMe || captured[1].Call.Status != "connected" {
		t.Fatalf("arah/status salah: %+v", captured)
	}
}

func TestCallOfferAndTerminationAreRecordedWithoutInventingAnswer(t *testing.T) {
	previous := onHistorySync
	t.Cleanup(func() { onHistorySync = previous })
	var captured []HistoricalMessage
	onHistorySync = func(_ uint, msgs []HistoricalMessage) (int, int, error) {
		captured = append(captured, msgs...)
		return len(msgs), 0, nil
	}
	jid := types.NewJID("628111111111", types.DefaultUserServer)
	meta := types.BasicCallMeta{From: jid, CallCreator: jid, CallID: "live-1", Timestamp: time.Unix(1788772200, 0)}
	w := &waInstance{agentID: 1, client: &whatsmeow.Client{}}
	w.handleEvent(&events.CallOffer{BasicCallMeta: meta})
	meta.Timestamp = meta.Timestamp.Add(20 * time.Second)
	w.handleEvent(&events.CallTerminate{BasicCallMeta: meta, Reason: "unknown"})
	if len(captured) != 2 {
		t.Fatalf("signaling panggilan hilang: %d", len(captured))
	}
	if captured[0].WAMsgID != captured[1].WAMsgID || captured[0].Sender != "628111111111" || captured[1].Call.Status != "ended" || captured[1].Call.DurationSeconds != nil {
		t.Fatalf("status/durasi ditebak atau ID berubah: %+v", captured)
	}
}

func TestAmbiguousCallRecordNeverCreatesPrivateThread(t *testing.T) {
	w := &waInstance{}
	record := &waSyncAction.CallLogRecord{CallID: proto.String("group-link"), CallCreatorJID: proto.String("628111111111@s.whatsapp.net"), IsIncoming: proto.Bool(true), IsCallLink: proto.Bool(true), StartTime: proto.Int64(1788772200)}
	if _, ok := w.historyCallRecord(record); ok {
		t.Fatal("call link tanpa identitas chat tidak boleh dianggap chat pribadi")
	}
}

func TestCallIdentityIncludesConversation(t *testing.T) {
	web := &waWeb.WebMessageInfo{Key: &waCommon.MessageKey{ID: proto.String("same-call-id")}, MessageTimestamp: proto.Uint64(1788772200), MessageStubType: waWeb.WebMessageInfo_CALL_MISSED_VOICE.Enum()}
	a, _ := historyCallMessage(web, "628111111111")
	b, _ := historyCallMessage(web, "628222222222")
	if a.WAMsgID == b.WAMsgID {
		t.Fatal("identitas panggilan tidak boleh menggabungkan dua percakapan")
	}
}
