// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"wa-assistant/backend/database"
	"wa-assistant/backend/models"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// Re-read and lock the persisted draft: an old button, incomplete form, or
// repeated delivery must not create a premature or duplicate order.
func confirmProductOrder(session models.ProductCheckoutSession, product models.Product, steps []checkoutStepConfig) productInteractionResult {
	result := productInteractionResult{handled: true}
	confirmed := false
	natural := conversationalAIFormEnabled(session.AgentID)
	err := database.DB.Transaction(func(tx *gorm.DB) error {
		var fresh models.ProductCheckoutSession
		if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ? AND agent_id = ? AND sender = ? AND product_id = ?", session.ID, session.AgentID, session.Sender, product.ID).First(&fresh).Error; err != nil {
			return err
		}
		if fresh.Status == "completed" {
			result.reply = "Pesanan ini sudah dikonfirmasi sebelumnya. Tidak ada pesanan baru yang dibuat."
			return nil
		}
		if time.Now().After(fresh.ExpiresAt) || (fresh.Status != "collecting" && fresh.Status != "confirming") {
			return fmt.Errorf("sesi pesanan tidak aktif")
		}
		if err := tx.Where("id = ? AND tenant_id = ?", fresh.ProductID, fresh.TenantID).First(&product).Error; err != nil {
			return err
		}
		if !productHasCheckout(product) {
			return fmt.Errorf("checkout produk tidak tersedia")
		}
		steps = parseCheckoutSteps(product)
		data := map[string]string{}
		if err := json.Unmarshal([]byte(fresh.DataJSON), &data); err != nil {
			return err
		}
		for i, step := range steps {
			if _, valid := checkoutAnswerValue(step, data[step.Key], "", fresh.ID); step.Required && (!valid || data["_incomplete_"+step.Key] == "true") {
				result = checkoutQuestion(fresh, product, step, i)
				if natural {
					fresh.StepIndex, fresh.Status = i, "collecting"
					result = productConversationResult(fresh, product, false)
				}
				return tx.Model(&fresh).Updates(map[string]any{"step_index": i, "status": "collecting"}).Error
			}
		}
		if fresh.Status != "confirming" {
			result = checkoutConfirmation(fresh, product, steps, natural)
			return tx.Model(&fresh).Update("status", "confirming").Error
		}
		editID, _ := strconv.ParseUint(data["_edit_order_id"], 10, 64)
		delete(data, "_edit_order_id")
		delete(data, confirmedOrderKey)
		delete(data, conversationEditKey)
		raw, _ := json.Marshal(data)
		summary := checkoutSummary(product, steps, string(raw))
		if editID > 0 {
			var order models.ProductOrder
			if err := tx.Where("id = ? AND agent_id = ? AND sender = ? AND product_id = ?", editID, fresh.AgentID, fresh.Sender, product.ID).First(&order).Error; err != nil {
				return err
			}
			if err := tx.Model(&order).Updates(map[string]any{"data_json": string(raw), "summary": summary, "status": "confirmed"}).Error; err != nil {
				return err
			}
			result.reply = "Pesanan *" + order.OrderCode + "* sudah diperbarui sesuai informasi terbaru."
			data[confirmedOrderKey] = strconv.FormatUint(uint64(order.ID), 10)
		} else {
			suffix := make([]byte, 6)
			if _, err := rand.Read(suffix); err != nil {
				return err
			}
			code := "ORD-" + time.Now().Format("060102") + "-" + strings.ToUpper(hex.EncodeToString(suffix))
			order := models.ProductOrder{TenantID: fresh.TenantID, AgentID: fresh.AgentID, ProductID: product.ID, Sender: fresh.Sender, OrderCode: code, Status: "confirmed", DataJSON: string(raw), Summary: summary}
			if err := tx.Create(&order).Error; err != nil {
				return err
			}
			message := strings.TrimSpace(product.CheckoutSuccessMessage)
			if message == "" {
				message = "Pesanan *{order_code}* berhasil dicatat. Terima kasih, CS kami akan memeriksa dan melanjutkan pesanan ini."
			}
			result.reply = strings.NewReplacer("{order_code}", code, "{product}", product.Name).Replace(message)
			data[confirmedOrderKey] = strconv.FormatUint(uint64(order.ID), 10)
		}
		raw, _ = json.Marshal(data)
		if err := tx.Model(&fresh).Updates(map[string]any{"status": "completed", "data_json": string(raw)}).Error; err != nil {
			return err
		}
		confirmed = true
		result.handoff = product.CheckoutHandoff || data["_vision_needs_human"] == "true"
		return nil
	})
	if err != nil {
		return productInteractionResult{handled: true, reply: "Pesanan belum berhasil disimpan. Silakan periksa datanya lalu konfirmasikan kembali."}
	}
	if confirmed {
		markProductLead(session.AgentID, session.Sender, "customer")
	}
	return result
}
