// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

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

func prepareAutomaticImageReply(agentID uint, sender, text string, result services.ChatResult) (models.ChatHistory, []byte, error) {
	row := models.ChatHistory{AgentID: agentID, Sender: sender, Reply: text, ReplyKind: models.ChatReplyKindAI, MediaType: "image", Mimetype: result.AttachmentMime, AIImageJSON: result.ImageSnapshotJSON(), AIEvidenceJSON: result.DeliveryEvidenceJSON(agentID, sender, text)}
	if row.AIImageJSON == "" || len([]rune(text)) > 1000 {
		return row, nil, fmt.Errorf("gambar belum divalidasi atau caption terlalu panjang")
	}
	data, err := os.ReadFile(result.AttachmentPath)
	if err != nil {
		return row, nil, err
	}
	if err := services.ValidateAIImageRetry(context.Background(), agentID, row.AIImageJSON, data); err != nil {
		return row, nil, err
	}
	// Store an independent copy so editing/deleting the source cannot break
	// already-delivered Inbox attachments or replace bytes waiting for retry.
	row.MediaPath = storeMedia(agentID, data, row.Mimetype, "")
	if row.MediaPath == "" {
		return row, nil, fmt.Errorf("salinan gambar tidak dapat disimpan")
	}
	row.FileName, row.MediaFetchStatus = filepath.Base(row.MediaPath), "available"
	return row, data, nil
}

func persistAutomaticReplyPart(agentID uint, sender, text, messageID string, handoffID uint, sendErr error) {
	persistAutomaticReplyPayload(models.ChatHistory{AgentID: agentID, Sender: sender, Reply: text, WAMsgID: strings.TrimSpace(messageID)}, handoffID, sendErr)
}

func persistAutomaticReplyPayload(row models.ChatHistory, handoffID uint, sendErr error) {
	if (strings.TrimSpace(row.Reply) == "" && row.MediaPath == "") || errors.Is(sendErr, errAutomaticReplyPaused) {
		return
	}
	status, message, retryAt := deliveryFields(sendErr)
	now := time.Now().Truncate(time.Second)
	row.DeliveryStatus, row.SendError, row.NextRetryAt, row.CreatedAt = status, message, retryAt, now
	if handoffID != 0 {
		row.ReplyKind, row.HandoffID = models.ChatReplyKindHandoff, handoffID
	}
	if row.ReplyKind == "" {
		row.ReplyKind = models.ChatReplyKindAutomation
	}
	result := database.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&row)
	if result.Error != nil {
		log.Printf("Gagal mencatat bubble AI agent=%d: %v", row.AgentID, result.Error)
		return
	}
	if result.RowsAffected > 0 {
		reconcileBufferedReceipt(row.AgentID, row.WAMsgID)
		touchInboxLastMsg(row.AgentID, row.Sender, now)
		if sendErr == nil {
			recordConversationResponse(row.AgentID, row.Sender, now, false)
		}
		publishInboxEvent(row.AgentID, row.Sender, "message")
	}
}
