package store_test

import (
	"testing"

	"github.com/wangjia/pangolin/server/internal/config"
	"github.com/wangjia/pangolin/server/internal/store"
)

// TestSQLiteMigrateUpDown verifies the SQLite migration set applies cleanly,
// is idempotent, seeds correctly, and rolls back — no container required, so it
// runs in normal CI (unlike the MySQL integration test behind //go:build integration).
func TestSQLiteMigrateUpDown(t *testing.T) {
	cfg := &config.Config{Driver: "sqlite", DSN: ":memory:"}
	db, err := store.Open(cfg)
	if err != nil {
		t.Fatalf("store.Open(sqlite): %v", err)
	}
	defer db.Close()

	// 1. MigrateUp.
	if err := store.MigrateUp(db, "sqlite"); err != nil {
		t.Fatalf("MigrateUp: %v", err)
	}
	v, dirty, err := store.MigrateVersion(db, "sqlite")
	if err != nil {
		t.Fatalf("MigrateVersion: %v", err)
	}
	if dirty {
		t.Fatalf("schema dirty after MigrateUp")
	}
	if v != 14 {
		t.Errorf("version = %d, want 14", v)
	}

	// 2. Core tables exist.
	for _, tbl := range []string{
		"users", "devices", "plans", "subscriptions", "code_batches", "codes",
		"usage_daily", "audit_log", "providers", "nodes", "node_events",
		"directory_version", "provision_idempotency", "replacements", "admins",
		"connect_credentials",
	} {
		var name string
		err := db.QueryRow(
			`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, tbl,
		).Scan(&name)
		if err != nil {
			t.Errorf("table %q missing: %v", tbl, err)
		}
	}

	// 3. Seed: 3 plans + directory_version singleton.
	var plans int
	if err := db.QueryRow(`SELECT COUNT(*) FROM plans`).Scan(&plans); err != nil {
		t.Fatalf("count plans: %v", err)
	}
	if plans != 3 {
		t.Errorf("plans seeded = %d, want 3", plans)
	}
	var dv int
	if err := db.QueryRow(`SELECT version FROM directory_version WHERE id=1`).Scan(&dv); err != nil {
		t.Errorf("directory_version singleton missing: %v", err)
	}

	// 4. Added columns from later migrations are present (000011 / 000013).
	if _, err := db.Exec(`SELECT reality_prk, reality_short_id, sub_token, totp_enabled FROM nodes
		LEFT JOIN users ON 0=1 LIMIT 0`); err != nil {
		// Separate queries — the join above is just a cheap column-existence probe.
		if _, e := db.Exec(`SELECT reality_prk, reality_short_id FROM nodes LIMIT 0`); e != nil {
			t.Errorf("nodes reality cols missing: %v", e)
		}
		if _, e := db.Exec(`SELECT sub_token, totp_secret_enc, totp_enabled FROM users LIMIT 0`); e != nil {
			t.Errorf("users totp cols missing: %v", e)
		}
	}

	// 5. Idempotent second MigrateUp.
	if err := store.MigrateUp(db, "sqlite"); err != nil {
		t.Fatalf("MigrateUp (idempotent): %v", err)
	}

	// 6. MigrateDown returns to baseline.
	if err := store.MigrateDown(db, "sqlite"); err != nil {
		t.Fatalf("MigrateDown: %v", err)
	}
	v2, _, err := store.MigrateVersion(db, "sqlite")
	if err != nil {
		t.Fatalf("MigrateVersion after down: %v", err)
	}
	if v2 != 0 {
		t.Errorf("version after down = %d, want 0", v2)
	}
}
