// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"errors"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"wa-assistant/backend/database"
	"wa-assistant/backend/models"
	"wa-assistant/backend/services"
)

type followUpReminderItem struct {
	ID             uint      `json:"id"`
	AgentID        uint      `json:"agent_id"`
	AgentName      string    `json:"agent_name"`
	Number         string    `json:"number"`
	Name           string    `json:"name"`
	Reason         string    `json:"reason"`
	DueAt          time.Time `json:"due_at"`
	AssignedUserID uint      `json:"assigned_user_id"`
	AssignedName   string    `json:"assigned_name"`
}

// Scope is checked on every poll and action; no connected-only filter, so an
// offline WhatsApp number cannot hide the operator's overdue work.
func reminderQuery(c *gin.Context) *gorm.DB {
	q := database.DB.WithContext(c.Request.Context()).Model(&models.FollowUpTask{}).
		Joins("JOIN agents a ON a.id = follow_up_tasks.agent_id").
		Joins("LEFT JOIN conversation_works cw ON cw.agent_id = follow_up_tasks.agent_id AND cw.sender = follow_up_tasks.number AND cw.status = 'open'").
		Joins(`LEFT JOIN users owner ON owner.id = cw.assigned_user_id AND owner.active = ? AND ((owner.tenant_id = a.tenant_id AND (owner.role IN ('admin', 'owner') OR owner.is_super_admin = ? OR EXISTS (SELECT 1 FROM user_agent_assignments oa WHERE oa.user_id = owner.id AND oa.agent_id = a.id AND oa.tenant_id = a.tenant_id))) OR (owner.is_super_admin = ? AND owner.tenant_id IS NULL))`, true, true, true).
		Where("a.tenant_id = ? AND follow_up_tasks.status = ?", currentTenantID(c), "pending")
	if !isTenantAdmin(c) {
		q = q.Where("EXISTS (SELECT 1 FROM user_agent_assignments uaa WHERE uaa.agent_id = a.id AND uaa.tenant_id = a.tenant_id AND uaa.user_id = ?)", currentUserID(c)).
			Where("owner.id IS NULL OR owner.id = ?", currentUserID(c))
	}
	return q
}

const reminderSelect = "follow_up_tasks.id, follow_up_tasks.agent_id, a.name AS agent_name, follow_up_tasks.number, follow_up_tasks.name, follow_up_tasks.reason, follow_up_tasks.due_at, COALESCE(owner.id, 0) AS assigned_user_id, COALESCE(owner.name, '') AS assigned_name"

func reminderKey(userID uint, task followUpReminderItem) string {
	return services.FollowUpKey("reminder", strconv.FormatUint(uint64(userID), 10), strconv.FormatUint(uint64(task.ID), 10), task.DueAt.UTC().Format(time.RFC3339Nano))
}

func ListFollowUpReminders(c *gin.Context) {
	now := time.Now()
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	if page < 1 {
		page = 1
	}
	if page > 10000 {
		page = 10000
	}
	var count int64
	if err := reminderQuery(c).Where("follow_up_tasks.due_at <= ?", now).Count(&count).Error; err != nil {
		reminderUnavailable(c)
		return
	}
	items := []followUpReminderItem{}
	if err := reminderQuery(c).Select(reminderSelect).Where("follow_up_tasks.due_at <= ?", now).Order("follow_up_tasks.due_at ASC, follow_up_tasks.id ASC").Offset((page - 1) * 50).Limit(50).Scan(&items).Error; err != nil {
		reminderUnavailable(c)
		return
	}
	var upcoming []followUpReminderItem
	if err := reminderQuery(c).Select(reminderSelect).Where("follow_up_tasks.due_at > ?", now).Order("follow_up_tasks.due_at ASC, follow_up_tasks.id ASC").Limit(1).Scan(&upcoming).Error; err != nil {
		reminderUnavailable(c)
		return
	}
	var next *followUpReminderItem
	if len(upcoming) > 0 {
		next = &upcoming[0]
	}
	var notificationIDs []uint
	if err := reminderQuery(c).
		Joins("LEFT JOIN follow_up_reminder_receipts rr ON rr.task_id = follow_up_tasks.id AND rr.user_id = ? AND rr.occurrence_at = follow_up_tasks.due_at", currentUserID(c)).
		Where("follow_up_tasks.due_at <= ? AND (owner.id IS NULL OR owner.id = ?) AND rr.notified_at IS NULL AND (rr.snoozed_until IS NULL OR rr.snoozed_until <= ?)", now, currentUserID(c), now).
		Order("follow_up_tasks.due_at ASC, follow_up_tasks.id ASC").Limit(50).Pluck("follow_up_tasks.id", &notificationIDs).Error; err != nil {
		reminderUnavailable(c)
		return
	}
	c.Header("Cache-Control", "no-store")
	c.JSON(200, gin.H{"notification_ids": notificationIDs, "due_count": count, "data": items, "next": next, "server_now": now, "timezone": "Asia/Jakarta"})
}

func reminderUnavailable(c *gin.Context) {
	c.JSON(503, gin.H{"error": "Pengingat belum bisa dimuat. Coba lagi."})
}

// Atomic receipt claims coordinate browsers/tabs and survive refresh/restarts.
// A client may display a toast only for the IDs actually claimed by this call.
func ClaimFollowUpReminders(c *gin.Context) {
	var req struct {
		IDs []uint `json:"ids"`
	}
	if c.ShouldBindJSON(&req) != nil || len(req.IDs) == 0 || len(req.IDs) > 50 {
		c.JSON(400, gin.H{"error": "Pilih maksimal 50 pengingat."})
		return
	}
	now := time.Now()
	items := []followUpReminderItem{}
	if err := reminderQuery(c).Select(reminderSelect).Where("follow_up_tasks.id IN ? AND follow_up_tasks.due_at <= ?", req.IDs, now).Scan(&items).Error; err != nil {
		reminderUnavailable(c)
		return
	}
	claimed := []followUpReminderItem{}
	for _, item := range items {
		// Supervisors can see all work on the dashboard; personal toasts go only to
		// the assignee, or the authorized team when nobody owns the chat.
		if item.AssignedUserID != 0 && item.AssignedUserID != currentUserID(c) {
			continue
		}
		key := reminderKey(currentUserID(c), item)
		receipt := models.FollowUpReminderReceipt{Key: key, TaskID: item.ID, AgentID: item.AgentID, UserID: currentUserID(c), OccurrenceAt: item.DueAt, NotifiedAt: &now}
		result := database.DB.WithContext(c.Request.Context()).Clauses(clause.OnConflict{DoNothing: true}).Create(&receipt)
		if result.Error != nil {
			reminderUnavailable(c)
			return
		}
		if result.RowsAffected == 0 {
			result = database.DB.WithContext(c.Request.Context()).Model(&models.FollowUpReminderReceipt{}).
				Where("`key` = ? AND notified_at IS NULL AND snoozed_until <= ?", key, now).
				Updates(map[string]any{"notified_at": now, "snoozed_until": nil})
			if result.Error != nil {
				reminderUnavailable(c)
				return
			}
		}
		if result.RowsAffected > 0 {
			claimed = append(claimed, item)
		}
	}
	c.JSON(200, gin.H{"data": claimed, "server_now": now})
}

func SnoozeFollowUpReminder(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("taskID"), 10, 32)
	if err != nil || id == 0 {
		c.JSON(404, gin.H{"error": "Pengingat tidak ditemukan."})
		return
	}
	now := time.Now()
	var items []followUpReminderItem
	if err := reminderQuery(c).Select(reminderSelect).Where("follow_up_tasks.id = ? AND follow_up_tasks.due_at <= ?", id, now).Limit(1).Scan(&items).Error; err != nil {
		reminderUnavailable(c)
		return
	}
	if len(items) == 0 {
		c.JSON(404, gin.H{"error": "Pengingat sudah berubah atau tidak tersedia."})
		return
	}
	until := now.Add(15 * time.Minute)
	receipt := models.FollowUpReminderReceipt{Key: reminderKey(currentUserID(c), items[0]), TaskID: uint(id), AgentID: items[0].AgentID, UserID: currentUserID(c), OccurrenceAt: items[0].DueAt, SnoozedUntil: &until}
	err = database.DB.WithContext(c.Request.Context()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "key"}}, DoUpdates: clause.Assignments(map[string]any{"notified_at": nil, "snoozed_until": until, "updated_at": now})}).Create(&receipt).Error
	if err != nil {
		reminderUnavailable(c)
		return
	}
	c.JSON(200, gin.H{"snoozed_until": until})
}

func GetFollowUpNotificationSettings(c *gin.Context) {
	id, ok := resolveAgent(c)
	if !ok {
		return
	}
	var settings models.FollowUpNotificationSetting
	err := database.DB.First(&settings, "agent_id = ?", id).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		reminderUnavailable(c)
		return
	}
	var latest models.FollowUpNotificationDelivery
	err = database.DB.Where("agent_id = ?", id).Order("id DESC").First(&latest).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		reminderUnavailable(c)
		return
	}
	var notice *models.FollowUpNotificationDelivery
	if err == nil {
		notice = &latest
	}
	c.JSON(200, gin.H{"settings": settings, "latest": notice})
}

func SaveFollowUpNotificationSettings(c *gin.Context) {
	id, ok := resolveAgent(c)
	if !ok {
		return
	}
	var req models.FollowUpNotificationSetting
	if c.ShouldBindJSON(&req) != nil {
		c.JSON(400, gin.H{"error": "Pengaturan tidak valid."})
		return
	}
	var err error
	if req.Enabled || req.Number != "" {
		req.Number, err = normalizeCSNotificationNumber(req.Number)
		if err != nil {
			c.JSON(400, gin.H{"error": err.Error()})
			return
		}
	}
	req.DashboardURL, err = normalizeHandoffInboxURL(req.DashboardURL)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	if req.Enabled {
		if err = validateCSNotificationDestination(database.DB, req.Number); err != nil {
			c.JSON(400, gin.H{"error": err.Error()})
			return
		}
	}
	req.AgentID = id
	// A fresh activation/configuration applies only to future due times. Editing
	// settings never forwards a backlog or retries uncertain notifications.
	req.EnabledAt = time.Now()
	if err = database.DB.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "agent_id"}}, DoUpdates: clause.AssignmentColumns([]string{"enabled", "number", "dashboard_url", "enabled_at", "updated_at"})}).Create(&req).Error; err != nil {
		reminderUnavailable(c)
		return
	}
	c.JSON(200, gin.H{"settings": req})
}

// Replies from the dedicated notification recipient are internal team messages.
func isFollowUpNotificationRecipient(agentID uint, number string) bool {
	var count int64
	return database.DB.Model(&models.FollowUpNotificationSetting{}).Where("agent_id = ? AND enabled = ? AND number = ?", agentID, true, number).Count(&count).Error == nil && count > 0
}
