// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"fmt"
	"log"
	"strings"
	"time"

	"gorm.io/gorm"
	"wa-assistant/backend/database"
	"wa-assistant/backend/models"
	"wa-assistant/backend/services"
)

const maxHandoffNotificationAttempts = 6

var handoffNotificationWake = make(chan struct{}, 1)

func internalNotificationID() (string, error) {
	var bytes [10]byte
	if _, err := rand.Read(bytes[:]); err != nil {
		return "", err
	}
	return "3EB0" + strings.ToUpper(hex.EncodeToString(bytes[:])), nil
}

func handoffNotificationText(agent models.Agent, row models.Handoff) string {
	reason := "Perlu bantuan atau pemeriksaan CS"
	switch row.Reason {
	case paymentVerificationReason:
		reason = "Bukti pembayaran perlu dicocokkan dengan mutasi oleh CS"
	case "customer_request":
		reason = "Pelanggan meminta dibantu CS manusia"
	case "sensitive_issue":
		reason = "Pembahasan sensitif perlu ditangani langsung oleh CS"
	case "customer_request_or_sensitive": // handoff lama sebelum alasan dipisah
		reason = "Pelanggan meminta bantuan CS atau pembahasan perlu ditangani langsung"
	}
	lines := []string{"*ChatLoop: pelanggan menunggu CS*", "", "Asisten: " + truncateRunes(agent.Name, 80), "Pelanggan: +" + row.Sender, "Keperluan: " + reason, "", "Pesan terakhir:", truncateRunes(row.LastMsg, 600)}
	if link := handoffInboxLink(agent.HandoffInboxURL, agent.ID, row.Sender); link != "" {
		lines = append(lines, "", "Buka percakapan:", link)
	} else {
		lines = append(lines, "", "Buka ChatLoop > Butuh CS untuk melihat percakapannya.")
	}
	lines = append(lines, "", "Ambil percakapannya dari Inbox. AI sedang dijeda; riwayat dan data layanan tersedia di sana.", "Ini notifikasi internal. Balas pelanggan melalui Inbox atau nomor layanan, bukan ke pesan ini.")
	return strings.Join(lines, "\n")
}

func enqueueHandoffNotification(tx *gorm.DB, agent models.Agent, row models.Handoff) error {
	if !agent.HandoffNotifyEnabled || agent.HandoffNotifyNumber == "" || agent.HandoffNotifyNumber == row.Sender {
		return nil
	}
	id, err := internalNotificationID()
	if err != nil {
		return err
	}
	now := time.Now()
	return tx.Create(&models.HandoffNotification{AgentID: agent.ID, HandoffID: row.ID, Recipient: agent.HandoffNotifyNumber, Message: handoffNotificationText(agent, row), MessageID: id, Status: "pending", NextAttemptAt: &now}).Error
}

func wakeHandoffNotifications() {
	select {
	case handoffNotificationWake <- struct{}{}:
	default:
	}
}

func isInternalHandoffNotification(agentID uint, messageID string) bool {
	if strings.TrimSpace(messageID) == "" {
		return false
	}
	var count int64
	if database.DB.Model(&models.HandoffNotification{}).Where("agent_id = ? AND message_id = ?", agentID, messageID).Count(&count).Error == nil && count > 0 {
		return true
	}
	return database.DB.Model(&models.FollowUpNotificationDelivery{}).Where("agent_id = ? AND message_id = ?", agentID, messageID).Count(&count).Error == nil && count > 0
}

func StartHandoffNotifications(ctx context.Context) {
	go func() {
		run := func() {
			safeRun("handoffNotifications", func() { processHandoffNotifications(ctx, time.Now(), sendHandoffNotification) })
		}
		run()
		ticker := time.NewTicker(15 * time.Second)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				run()
			case <-handoffNotificationWake:
				run()
			}
		}
	}()
}

type handoffNotificationSender func(context.Context, models.HandoffNotification) error

func sendHandoffNotification(ctx context.Context, row models.HandoffNotification) error {
	return services.WA(row.AgentID).SendInternalNotification(ctx, row.Recipient, row.Message, row.MessageID)
}

// The lease is acquired by an atomic compare-and-update, so two workers cannot
// send the same job concurrently. Stale workers cannot overwrite a newer result.
func processHandoffNotifications(ctx context.Context, now time.Time, send handoffNotificationSender) {
	db := database.DB
	const due = "(status = ? AND next_attempt_at <= ?) OR (status = ? AND locked_until <= ?)"
	var rows []models.HandoffNotification
	if err := db.Where(due, "pending", now, "sending", now).Order("id asc").Limit(20).Find(&rows).Error; err != nil {
		log.Printf("handoff notification queue unavailable: %v", err)
		return
	}
	for _, row := range rows {
		if ctx.Err() != nil {
			return
		}
		token, err := internalNotificationID()
		if err != nil {
			return
		}
		until := time.Now().Add(2 * time.Minute)
		lease := db.Model(&models.HandoffNotification{}).Where("id = ?", row.ID).Where(due, "pending", now, "sending", now).Updates(map[string]any{"status": "sending", "locked_until": until, "lock_token": token})
		if lease.Error != nil || lease.RowsAffected == 0 {
			continue
		}
		owned := func() *gorm.DB {
			return db.Model(&models.HandoffNotification{}).Where("id = ? AND status = ? AND lock_token = ?", row.ID, "sending", token)
		}
		cancel := func(reason string) {
			_ = owned().Updates(map[string]any{"status": "cancelled", "last_error": reason, "next_attempt_at": nil, "locked_until": nil}).Error
		}
		var handoff models.Handoff
		err = db.Where("id = ? AND agent_id = ?", row.HandoffID, row.AgentID).First(&handoff).Error
		if errors.Is(err, gorm.ErrRecordNotFound) || (err == nil && handoff.Status != "waiting") {
			cancel("Percakapan sudah ditangani atau dikembalikan ke AI")
			continue
		}
		var agent models.Agent
		if err == nil {
			err = db.First(&agent, row.AgentID).Error
		}
		if errors.Is(err, gorm.ErrRecordNotFound) {
			cancel("Nomor layanan sudah dihapus")
			continue
		}
		if err == nil && (!agent.HandoffNotifyEnabled || agent.HandoffNotifyNumber != row.Recipient || handoff.Sender == row.Recipient) {
			cancel("Pengaturan notifikasi berubah")
			continue
		}
		if err == nil {
			err = validateCSNotificationDestination(db, row.Recipient)
		}
		// Refresh ownership after reading configuration, just before the send.
		var active int64
		if err == nil {
			err = owned().Count(&active).Error
		}
		if err == nil && active == 0 {
			continue
		}
		if err == nil {
			sendCtx, stop := context.WithTimeout(ctx, 40*time.Second)
			err = send(sendCtx, row)
			stop()
		}
		if ctx.Err() != nil {
			return
		} // lease recovery retains the original message ID
		attempts := row.Attempts + 1
		updates := map[string]any{"attempts": attempts, "locked_until": nil, "next_attempt_at": nil, "last_error": ""}
		if err == nil {
			updates["status"], updates["sent_at"] = "sent", time.Now()
		} else {
			updates["last_error"] = "Notifikasi belum terkirim. Periksa koneksi WhatsApp dan nomor CS."
			if attempts >= maxHandoffNotificationAttempts {
				updates["status"] = "failed"
			} else {
				updates["status"] = "pending"
				next := now.Add(time.Minute * time.Duration(1<<min(attempts-1, 4)))
				updates["next_attempt_at"] = next
			}
		}
		if updateErr := owned().Updates(updates).Error; updateErr != nil {
			log.Printf("handoff notification %d status could not be saved: %v", row.ID, updateErr)
		}
	}
	// Retain delivery diagnostics for seven days, without keeping internal copies
	// of customer messages indefinitely. Pending work is never pruned here.
	if err := db.Where("created_at < ? AND status IN ?", now.Add(-7*24*time.Hour), []string{"sent", "failed", "cancelled"}).Delete(&models.HandoffNotification{}).Error; err != nil {
		log.Print(fmt.Errorf("handoff notification cleanup: %w", err))
	}
}
