package db

import (
	"testing"
	"time"
)

// TestMoveMessageToTrashAndRestore confirms a message trashed via MoveMessageToTrash
// remembers its prior folder and RestoreMessage puts it back there.
func TestMoveMessageToTrashAndRestore(t *testing.T) {
	d := openTestDB(t)
	const mailboxID = int64(1)

	uid, err := d.InsertMessage(mailboxID, "Newsletters", "", "", time.Now(), 10, "/dev/null", []byte("nonce"), "a@example.com", "b@example.com", "subj", "")
	if err != nil {
		t.Fatal(err)
	}
	if err := d.MoveMessageToTrash(mailboxID, uid); err != nil {
		t.Fatal(err)
	}
	msg, err := d.GetMessageByUID(mailboxID, uid)
	if err != nil || msg.Folder != "Trash" {
		t.Fatalf("expected message in Trash, got folder=%q (err=%v)", msg.Folder, err)
	}

	if err := d.RestoreMessage(mailboxID, uid); err != nil {
		t.Fatal(err)
	}
	msg, err = d.GetMessageByUID(mailboxID, uid)
	if err != nil || msg.Folder != "Newsletters" {
		t.Fatalf("expected message restored to Newsletters, got folder=%q (err=%v)", msg.Folder, err)
	}
}

// TestRestoreMessageFallsBackToInboxWhenUnknown confirms a message with no recorded
// restore_folder (e.g. trashed before this feature existed) restores to INBOX rather
// than erroring or restoring to an empty folder name.
func TestRestoreMessageFallsBackToInboxWhenUnknown(t *testing.T) {
	d := openTestDB(t)
	const mailboxID = int64(1)

	uid, err := d.InsertMessage(mailboxID, "Trash", "", "", time.Now(), 10, "/dev/null", []byte("nonce"), "a@example.com", "b@example.com", "subj", "")
	if err != nil {
		t.Fatal(err)
	}
	if err := d.RestoreMessage(mailboxID, uid); err != nil {
		t.Fatal(err)
	}
	msg, err := d.GetMessageByUID(mailboxID, uid)
	if err != nil || msg.Folder != "INBOX" {
		t.Fatalf("expected fallback to INBOX, got folder=%q (err=%v)", msg.Folder, err)
	}
}
