// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"context"
	"errors"
	"fmt"
	"log"
	"strings"
	"time"

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

const followUpEscalationDelay = 5 * time.Minute

func StartFollowUpReminderNotifications(ctx context.Context) {
	go func() {
		ticker := time.NewTicker(30 * time.Second)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				safeRun("followUpReminderNotifications", func() {
					dispatchFollowUpReminderNotifications(ctx, database.DB, time.Now(), followUpTaskConnected, func(ctx context.Context, agentID uint, number, text, messageID string) error {
						return services.WA(agentID).SendInternalNotification(ctx, number, text, messageID)
					})
				})
			}
		}
	}()
}

type followUpNotificationSender func(context.Context, uint, string, string, string) error

// At most one bounded message per workspace in a tick, containing up to ten
// reminders. All claims are stored before sending; a timeout/crash cannot trigger
// a blind retry. The ordinary dashboard queue remains authoritative.
func dispatchFollowUpReminderNotifications(ctx context.Context, db *gorm.DB, now time.Time, connected func(uint) bool, send followUpNotificationSender) {
	var settings []models.FollowUpNotificationSetting
	if err := db.WithContext(ctx).Where("enabled = ?", true).Find(&settings).Error; err != nil {
		log.Print("Follow-up: pengaturan notifikasi belum bisa dibaca")
		return
	}
	for _, setting := range settings {
		if ctx.Err() != nil {
			return
		}
		if !connected(setting.AgentID) {
			continue
		}
		if validateCSNotificationDestination(db, setting.Number) != nil {
			continue
		}
		var agent models.Agent
		if db.WithContext(ctx).First(&agent, setting.AgentID).Error != nil {
			continue
		}
		tasks := []models.FollowUpTask{}
		// Exclude previously attempted occurrences before LIMIT, otherwise old rows
		// could starve later reminders. Compare the same precision stored by GORM.
		if err := db.WithContext(ctx).Where("agent_id = ? AND status = ? AND due_at >= ? AND due_at <= ? AND number <> ?", setting.AgentID, "pending", setting.EnabledAt, now.Add(-followUpEscalationDelay), setting.Number).
			Where("NOT EXISTS (SELECT 1 FROM follow_up_notification_deliveries d WHERE d.task_id = follow_up_tasks.id AND d.occurrence_at = follow_up_tasks.due_at)").
			Order("due_at ASC, id ASC").Limit(10).Find(&tasks).Error; err != nil {
			log.Print("Follow-up: antrean notifikasi belum bisa dibaca")
			continue
		}
		if len(tasks) == 0 {
			continue
		}
		messageID, err := internalNotificationID()
		if err != nil {
			return
		}
		deliveries := []models.FollowUpNotificationDelivery{}
		accepted := []models.FollowUpTask{}
		for _, task := range tasks {
			row := models.FollowUpNotificationDelivery{Key: services.FollowUpKey("followup-wa", fmt.Sprint(task.ID), task.DueAt.UTC().Format(time.RFC3339Nano)), TaskID: task.ID, AgentID: task.AgentID, OccurrenceAt: task.DueAt, Recipient: setting.Number, MessageID: messageID, Status: "sending"}
			result := db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&row)
			if result.Error != nil {
				continue
			}
			if result.RowsAffected > 0 {
				deliveries = append(deliveries, row)
				accepted = append(accepted, task)
			}
		}
		if len(accepted) == 0 {
			continue
		}
		finish := func(ids []uint, status string) {
			if len(ids) == 0 {
				return
			}
			updates := map[string]any{"status": status}
			if status == "sent" {
				updates["sent_at"] = time.Now()
			}
			finishCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
			defer cancel()
			if err := db.WithContext(finishCtx).Model(&models.FollowUpNotificationDelivery{}).Where("id IN ? AND message_id = ? AND status = ?", ids, messageID, "sending").Updates(updates).Error; err != nil {
				log.Print("Follow-up: status notifikasi belum tersimpan; jangan kirim ulang")
			}
		}
		// Only release claims when SendInternalNotification has NEVER been called.
		// This lets a transient read failure or disconnect recover on the next tick.
		release := func(ids []uint) {
			if len(ids) == 0 {
				return
			}
			releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
			defer cancel()
			if err := db.WithContext(releaseCtx).Where("id IN ? AND message_id = ? AND status = ?", ids, messageID, "sending").Delete(&models.FollowUpNotificationDelivery{}).Error; err != nil {
				log.Print("Follow-up: klaim sebelum pengiriman belum dapat dilepas")
			}
		}
		ids := []uint{}
		for _, row := range deliveries {
			ids = append(ids, row.ID)
		}
		var current models.FollowUpNotificationSetting
		if err := db.WithContext(ctx).First(&current, "agent_id = ?", setting.AgentID).Error; err != nil {
			release(ids)
			continue
		}
		if !current.Enabled || current.Number != setting.Number || !current.EnabledAt.Equal(setting.EnabledAt) {
			finish(ids, "cancelled")
			continue
		}
		if !connected(setting.AgentID) {
			release(ids)
			continue
		}
		valid := []models.FollowUpTask{}
		validIDs := []uint{}
		for i, task := range accepted {
			var latest models.FollowUpTask
			err := db.WithContext(ctx).Where("id = ? AND agent_id = ? AND status = ? AND number <> ?", task.ID, setting.AgentID, "pending", setting.Number).First(&latest).Error
			if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
				release([]uint{deliveries[i].ID})
				continue
			}
			if err != nil || !latest.DueAt.Equal(task.DueAt) {
				finish([]uint{deliveries[i].ID}, "cancelled")
				continue
			}
			valid = append(valid, latest)
			validIDs = append(validIDs, deliveries[i].ID)
		}
		if len(valid) == 0 {
			continue
		}
		if ctx.Err() != nil {
			release(validIDs)
			continue
		}
		if validateCSNotificationDestination(db, setting.Number) != nil {
			finish(validIDs, "cancelled")
			continue
		}
		lines := []string{"*ChatLoop: tindak lanjut menunggu*", "Asisten: " + truncateRunes(agent.Name, 80), ""}
		for _, task := range valid {
			name := task.Name
			if name == "" {
				name = "+" + task.Number
			}
			lines = append(lines, "- "+truncateRunes(name, 80)+" · "+task.DueAt.In(services.FollowUpLocation).Format("02 Jan 15.04 WIB"), "  "+truncateRunes(task.Reason, 160))
		}
		if link := handoffInboxLink(setting.DashboardURL, setting.AgentID, valid[0].Number); link != "" {
			lines = append(lines, "", "Buka Inbox: "+link)
		}
		lines = append(lines, "", "Buka Follow-up di ChatLoop, tinjau pesan, lalu hubungi pelanggan. Ini pengingat internal; belum ada pesan yang dikirim ke pelanggan.")
		sendCtx, cancel := context.WithTimeout(ctx, 40*time.Second)
		err = send(sendCtx, setting.AgentID, setting.Number, strings.Join(lines, "\n"), messageID)
		cancel()
		if err != nil {
			finish(validIDs, "uncertain")
		} else {
			finish(validIDs, "sent")
		}
	}
}
