// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"crypto/sha256"
	"fmt"
	"log"
	"strings"
	"time"

	"go.mau.fi/whatsmeow/proto/waCommon"
	"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"
	"wa-assistant/backend/models"
)

// Call IDs are not message stanza IDs: keep their namespace separate and bounded.
func callHistoryID(sender, id string) string {
	sum := sha256.Sum256([]byte(NormalizeInboxSender(sender) + "\x00" + strings.TrimSpace(id)))
	return fmt.Sprintf("call-%x", sum[:24])
}

func historyCallMessage(web *waWeb.WebMessageInfo, sender string) (HistoricalMessage, bool) {
	if web == nil || web.GetKey().GetID() == "" || sender == "" || web.GetMessageTimestamp() == 0 {
		return HistoricalMessage{}, false
	}
	call := &models.CallLog{Source: "stub", Kind: "voice", Status: "missed", Incoming: !web.GetKey().GetFromMe()}
	switch web.GetMessageStubType() {
	case waWeb.WebMessageInfo_CALL_MISSED_VOICE, waWeb.WebMessageInfo_CALL_MISSED_GROUP_VOICE:
	case waWeb.WebMessageInfo_CALL_MISSED_VIDEO, waWeb.WebMessageInfo_CALL_MISSED_GROUP_VIDEO:
		call.Kind = "video"
	default:
		native := unwrapHistoryMessage(web.GetMessage()).GetCallLogMesssage()
		if native == nil {
			return HistoricalMessage{}, false
		}
		call.Source = "message"
		call.Status = "unknown"
		if native.GetIsVideo() {
			call.Kind = "video"
		}
		if native.CallOutcome != nil {
			call.Status = callOutcome(native.GetCallOutcome().String())
		}
		if native.DurationSecs != nil && native.GetDurationSecs() >= 0 {
			duration := native.GetDurationSecs()
			call.DurationSeconds = &duration
		}

	}
	return HistoricalMessage{Sender: sender, FromMe: !call.Incoming, MediaType: "call", Call: call, WAMsgID: callHistoryID(sender, web.GetKey().GetID()), Timestamp: time.Unix(int64(web.GetMessageTimestamp()), 0)}, true
}

func callOutcome(outcome string) string {
	switch outcome {
	case "CONNECTED":
		return "connected"
	case "MISSED":
		return "missed"
	case "REJECTED":
		return "rejected"
	case "CANCELLED", "ABANDONED":
		return "cancelled"
	case "ACCEPTEDELSEWHERE", "ACCEPTED_ELSEWHERE":
		return "accepted_elsewhere"
	case "FAILED", "UNAVAILABLE", "INVALID":
		return "failed"
	case "ONGOING":
		return "ongoing"
	case "SILENCED_BY_DND", "SILENCED_UNKNOWN_CALLER":
		return "silenced"
	default:
		return "unknown"
	}
}

// Only route to a known WhatsApp chat. Never guess a phone number from an LID
// or assign a group call to an arbitrary participant.
func (w *waInstance) callSender(jid types.JID) string {
	if jid.Server == types.GroupServer {
		return NormalizeInboxSender(jid.String())
	}
	number, err := phoneNumberForJID(context.Background(), w.client, jid)
	if err != nil {
		return ""
	}
	return NormalizeInboxSender(number)
}

func (w *waInstance) historyCallRecord(record *waSyncAction.CallLogRecord) (HistoricalMessage, bool) {
	if record == nil || strings.TrimSpace(record.GetCallID()) == "" || record.IsIncoming == nil || record.GetStartTime() <= 0 {
		return HistoricalMessage{}, false
	}
	if record.GetGroupJID() == "" && (record.GetIsCallLink() || len(record.GetParticipants()) > 2) {
		return HistoricalMessage{}, false
	}
	var chat types.JID
	if group := record.GetGroupJID(); group != "" {
		parsed, err := types.ParseJID(group)
		if err != nil || parsed.Server != types.GroupServer {
			return HistoricalMessage{}, false
		}
		chat = parsed
	} else if record.GetIsIncoming() {
		chat, _ = types.ParseJID(record.GetCallCreatorJID())
	} else {
		creator, _ := types.ParseJID(record.GetCallCreatorJID())
		if creator.IsEmpty() {
			return HistoricalMessage{}, false
		}
		peers := map[string]types.JID{}
		for _, participant := range record.GetParticipants() {
			jid, err := types.ParseJID(participant.GetUserJID())
			if err != nil || jid.IsEmpty() {
				continue
			}
			if jid.ToNonAD() == creator.ToNonAD() {
				continue
			}
			if w.client != nil && w.client.Store != nil && ((w.client.Store.ID != nil && jid.ToNonAD() == w.client.Store.ID.ToNonAD()) || jid.ToNonAD() == w.client.Store.LID.ToNonAD()) {
				continue
			}
			number := w.callSender(jid)
			if number != "" && number != w.callSender(creator) {
				peers[number] = jid
			}
		}
		if len(peers) != 1 {
			return HistoricalMessage{}, false
		}
		for _, jid := range peers {
			chat = jid
		}
	}
	sender := w.callSender(chat)
	if sender == "" {
		return HistoricalMessage{}, false
	}
	ts := time.Unix(record.GetStartTime(), 0)
	if record.GetStartTime() >= 1e12 {
		ts = time.UnixMilli(record.GetStartTime())
	}
	if ts.Year() < 2020 || ts.Year() > 2100 {
		return HistoricalMessage{}, false
	}
	call := &models.CallLog{Source: "record", Kind: "voice", Status: "unknown", Incoming: record.GetIsIncoming()}
	if record.GetIsVideo() {
		call.Kind = "video"
	}
	if record.CallResult != nil {
		call.Status = callOutcome(record.GetCallResult().String())
	}
	// CallLogMessage.durationSecs has an explicit unit; the sync record's
	// unqualified duration is not displayed until its unit is verified.
	return HistoricalMessage{Sender: sender, FromMe: !call.Incoming, MediaType: "call", Call: call, WAMsgID: callHistoryID(sender, record.GetCallID()), Timestamp: ts}, true
}

func (w *waInstance) storeLiveCall(message HistoricalMessage) {
	if onHistorySync == nil {
		return
	}
	if _, _, err := onHistorySync(w.agentID, []HistoricalMessage{message}); err != nil {
		log.Printf("WA agent %d: gagal menyimpan log panggilan: %v", w.agentID, err)
	}
}

func (w *waInstance) handleCallMessage(event *events.Message) bool {
	web := event.SourceWebMsg
	if unwrapHistoryMessage(event.Message).GetCallLogMesssage() == nil {
		switch web.GetMessageStubType() {
		case waWeb.WebMessageInfo_CALL_MISSED_VOICE, waWeb.WebMessageInfo_CALL_MISSED_VIDEO, waWeb.WebMessageInfo_CALL_MISSED_GROUP_VOICE, waWeb.WebMessageInfo_CALL_MISSED_GROUP_VIDEO:
		default:
			return false
		}
	}
	if web == nil {
		web = &waWeb.WebMessageInfo{}
	}
	// Do not mutate the event shared with other consumers.
	web = proto.Clone(web).(*waWeb.WebMessageInfo)
	web.Key = &waCommon.MessageKey{ID: proto.String(event.Info.ID), FromMe: proto.Bool(event.Info.IsFromMe)}
	web.Message = event.Message
	if !event.Info.Timestamp.IsZero() {
		web.MessageTimestamp = proto.Uint64(uint64(event.Info.Timestamp.Unix()))
	}
	// Detect first, resolve identities only for a call log. This never invokes AI,
	// auto-read, media downloads or the outgoing message handler.
	probe, ok := historyCallMessage(web, "probe")
	if !ok {
		return true
	}
	sender := w.callSender(event.Info.Chat)
	if sender == "" && !event.Info.IsGroup {
		sender = inboxPresenceSender(w.client, event.Info.MessageSource)
	}
	if sender != "" {
		probe.Sender = sender
		probe.WAMsgID = callHistoryID(sender, event.Info.ID)
		w.storeLiveCall(probe)
	}
	return true
}

// A signaling event proves a call existed, not that anyone answered it. Detailed
// call records can replace these neutral entries later using the same call ID.
func (w *waInstance) recordCallSignal(meta types.BasicCallMeta, status, kind string, offered bool) {
	if meta.CallID == "" || meta.Timestamp.Year() < 2020 {
		return
	}
	creator := meta.CallCreator
	if creator.Server == types.HiddenUserServer && !meta.CallCreatorAlt.IsEmpty() {
		creator = meta.CallCreatorAlt
	}
	incoming := true
	if !offered {
		if w.client != nil && w.client.Store != nil && w.client.Store.ID != nil {
			incoming = creator.ToNonAD() != w.client.Store.ID.ToNonAD() && creator.ToNonAD() != w.client.Store.LID.ToNonAD()
		} else if w.callSender(creator) == "" || w.callSender(creator) != w.callSender(meta.From) {
			return
		}
	}
	chat := creator
	if !incoming {
		chat = meta.From
	}
	if !meta.GroupJID.IsEmpty() {
		if meta.GroupJID.Server != types.GroupServer {
			return
		}
		chat = meta.GroupJID
	}
	sender := w.callSender(chat)
	if sender == "" {
		return
	}
	w.storeLiveCall(HistoricalMessage{Sender: sender, FromMe: !incoming, WAMsgID: callHistoryID(sender, meta.CallID), MediaType: "call", Timestamp: meta.Timestamp, Call: &models.CallLog{Source: "signal", Kind: kind, Status: status, Incoming: incoming}})
}
