package db

import (
	"context"
	"path/filepath"
	"sort"
	"testing"
)

func TestBootstrapCreatesAllTables(t *testing.T) {
	tmp := filepath.Join(t.TempDir(), "test.db")
	d, err := Open(tmp)
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	defer d.Close()

	if err := Bootstrap(context.Background(), d); err != nil {
		t.Fatalf("bootstrap: %v", err)
	}

	want := []string{"accounts", "clipboard_state", "devices", "login_requests", "push_subscriptions", "shortcut_tokens", "transfer_sessions", "web_sessions"}
	rows, err := d.Query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
	if err != nil {
		t.Fatalf("query tables: %v", err)
	}
	defer rows.Close()

	var got []string
	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			t.Fatalf("scan: %v", err)
		}
		got = append(got, name)
	}
	sort.Strings(got)
	if len(got) != len(want) {
		t.Fatalf("table count: got %v, want %v", got, want)
	}
	for i := range want {
		if got[i] != want[i] {
			t.Errorf("table[%d]: got %q, want %q", i, got[i], want[i])
		}
	}
}

func TestBootstrapIsIdempotent(t *testing.T) {
	tmp := filepath.Join(t.TempDir(), "test.db")
	d, err := Open(tmp)
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	defer d.Close()

	for i := 0; i < 3; i++ {
		if err := Bootstrap(context.Background(), d); err != nil {
			t.Fatalf("bootstrap iter %d: %v", i, err)
		}
	}
}

func TestOpenEnablesWALMode(t *testing.T) {
	tmp := filepath.Join(t.TempDir(), "test.db")
	d, err := Open(tmp)
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	defer d.Close()

	var mode string
	if err := d.QueryRow("PRAGMA journal_mode").Scan(&mode); err != nil {
		t.Fatalf("pragma: %v", err)
	}
	if mode != "wal" {
		t.Errorf("journal_mode: got %q, want %q", mode, "wal")
	}
}

// Simulates the prod upgrade: a clipboard_state created before the version
// column existed must gain it (defaulting to 0) on bootstrap, idempotently.
func TestBootstrapAddsClipboardVersionToLegacyDB(t *testing.T) {
	tmp := filepath.Join(t.TempDir(), "legacy.db")
	d, err := Open(tmp)
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	defer d.Close()

	_, err = d.Exec(`CREATE TABLE clipboard_state (
		user_id TEXT PRIMARY KEY, content_type TEXT NOT NULL, content TEXT,
		source_device TEXT, updated_at INTEGER NOT NULL)`)
	if err != nil {
		t.Fatalf("legacy schema: %v", err)
	}
	if _, err := d.Exec(`INSERT INTO clipboard_state (user_id, content_type, content, updated_at)
		VALUES ('u', 'text/plain', 'hi', 100)`); err != nil {
		t.Fatalf("seed row: %v", err)
	}

	if err := Bootstrap(context.Background(), d); err != nil {
		t.Fatalf("bootstrap: %v", err)
	}

	var version int64
	if err := d.QueryRow(`SELECT version FROM clipboard_state WHERE user_id='u'`).Scan(&version); err != nil {
		t.Fatalf("select version (column missing?): %v", err)
	}
	if version != 0 {
		t.Errorf("legacy row version: got %d, want 0", version)
	}
	// Second bootstrap must be a no-op (column already present).
	if err := Bootstrap(context.Background(), d); err != nil {
		t.Fatalf("second bootstrap: %v", err)
	}
}

// Simulates the prod upgrade for scan-login: a web_sessions table created before
// kind/scope/granted_by existed must gain them, with an existing row defaulting
// to a normal OIDC-backed full session so its behaviour is unchanged (AUTH.md §2.2).
func TestBootstrapAddsWebSessionColumnsToLegacyDB(t *testing.T) {
	tmp := filepath.Join(t.TempDir(), "legacy.db")
	d, err := Open(tmp)
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	defer d.Close()

	_, err = d.Exec(`CREATE TABLE web_sessions (
		id TEXT PRIMARY KEY, user_id TEXT NOT NULL, refresh_token TEXT NOT NULL,
		device_name TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '',
		created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL, expires_at INTEGER NOT NULL)`)
	if err != nil {
		t.Fatalf("legacy schema: %v", err)
	}
	if _, err := d.Exec(`INSERT INTO web_sessions (id, user_id, refresh_token, created_at, last_used_at, expires_at)
		VALUES ('s', 'u', 'enc', 1, 1, 9999999999)`); err != nil {
		t.Fatalf("seed row: %v", err)
	}

	if err := Bootstrap(context.Background(), d); err != nil {
		t.Fatalf("bootstrap: %v", err)
	}

	var kind, scope, grantedBy string
	if err := d.QueryRow(`SELECT kind, scope, granted_by FROM web_sessions WHERE id='s'`).
		Scan(&kind, &scope, &grantedBy); err != nil {
		t.Fatalf("select new columns (missing?): %v", err)
	}
	if kind != "oidc" || scope != "full" || grantedBy != "" {
		t.Errorf("legacy row defaults: got kind=%q scope=%q granted_by=%q, want oidc/full/empty",
			kind, scope, grantedBy)
	}
	// Idempotent: second bootstrap must not error on already-present columns.
	if err := Bootstrap(context.Background(), d); err != nil {
		t.Fatalf("second bootstrap: %v", err)
	}
}
