package inbox

import (
	"path/filepath"
	"testing"
)

func TestInitCreatesSchemaOnEmptyDB(t *testing.T) {
	t.Parallel()

	dbPath := filepath.Join(t.TempDir(), "coord.db")
	initOut := runInboxCommand(t, "--db", dbPath, "--json", "init")

	var initResp map[string]any
	mustDecodeJSON(t, initOut, &initResp)

	if ok, _ := initResp["ok"].(bool); !ok {
		t.Fatalf("expected ok=true, got %#v", initResp)
	}
	if cmd, _ := initResp["command"].(string); cmd != "init" {
		t.Fatalf("expected command init, got %#v", initResp["command"])
	}
	if got := nestedString(t, initResp, "data", "db_path"); got != dbPath {
		t.Fatalf("expected db_path %q, got %q", dbPath, got)
	}
	if got := nestedString(t, initResp, "data", "status"); got != "initialized" {
		t.Fatalf("expected initialized status, got %q", got)
	}
}

func TestInitIsIdempotentOnExistingDB(t *testing.T) {
	t.Parallel()

	dbPath := filepath.Join(t.TempDir(), "coord.db")

	firstOut := runInboxCommand(t, "--db", dbPath, "--json", "init")
	secondOut := runInboxCommand(t, "--db", dbPath, "--json", "init")

	var firstResp map[string]any
	var secondResp map[string]any
	mustDecodeJSON(t, firstOut, &firstResp)
	mustDecodeJSON(t, secondOut, &secondResp)

	if got := nestedString(t, firstResp, "data", "status"); got != "initialized" {
		t.Fatalf("expected first init status initialized, got %q", got)
	}
	if got := nestedString(t, secondResp, "data", "status"); got != "initialized" {
		t.Fatalf("expected second init status initialized, got %q", got)
	}
	if got := nestedString(t, firstResp, "data", "db_path"); got != dbPath {
		t.Fatalf("expected first db_path %q, got %q", dbPath, got)
	}
	if got := nestedString(t, secondResp, "data", "db_path"); got != dbPath {
		t.Fatalf("expected second db_path %q, got %q", dbPath, got)
	}
}

func initCommandTestDB(t *testing.T) string {
	t.Helper()

	dbPath := filepath.Join(t.TempDir(), "coord.db")
	runInboxCommand(t, "--db", dbPath, "--json", "init")
	return dbPath
}

func sendPendingThread(t *testing.T, dbPath, from, to, subject, summary string) string {
	t.Helper()

	sendOut := runInboxCommand(
		t,
		"--db", dbPath,
		"--json",
		"send",
		"--from", from,
		"--to", to,
		"--subject", subject,
		"--summary", summary,
	)

	var sendResp map[string]any
	mustDecodeJSON(t, sendOut, &sendResp)
	return nestedString(t, sendResp, "data", "thread", "thread_id")
}
