package userbehavior

import (
	"time"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var _ = Describe("GTMSentEmail model", func() {
	It("supports queued delivery columns and nullable sent_at", func() {
		db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
		Expect(err).ToNot(HaveOccurred())

		err = db.AutoMigrate(&GTMSentEmail{})
		Expect(err).ToNot(HaveOccurred())

		Expect(db.Migrator().HasColumn("gtm_sent_emails", "scheduled_at")).To(BeTrue())
		Expect(db.Migrator().HasColumn("gtm_sent_emails", "attempt_count")).To(BeTrue())
		Expect(db.Migrator().HasColumn("gtm_sent_emails", "last_attempt_at")).To(BeTrue())

		messageID := "msg_123"
		ccAddresses := "cc@example.com"
		customerRefs := "Customer A, Customer B"

		now := time.Now()
		res := db.Exec(
			`INSERT INTO gtm_sent_emails
				(created_at, lead_id, tenant_id, to_address, subject, body, cc_addresses, use_case_profile, customer_references,
				 scheduled_at, sent_at, status, attempt_count, last_attempt_at, message_id, error_message)
			 VALUES
				(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, NULL, ?, NULL)`,
			now,
			1,
			123,
			"recipient@example.com",
			"Test Subject",
			"This is the email body content",
			ccAddresses,
			"ai_chatbot",
			customerRefs,
			now,
			"queued",
			0,
			messageID,
		)
		Expect(res.Error).ToNot(HaveOccurred())

		var count int64
		Expect(db.Table("gtm_sent_emails").Count(&count).Error).ToNot(HaveOccurred())
		Expect(count).To(Equal(int64(1)))
	})
})
