package db

import (
	"testing"
	"time"
)

// TestSQLiteTimeRoundTrip de-risks the migration translation: confirm modernc
// SQLite reads a DATETIME column back into a Go time.Time (UTC) correctly.
func TestSQLiteTimeRoundTrip(t *testing.T) {
	d, err := OpenDriver("sqlite", ":memory:")
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	defer d.Close()

	if _, err := d.Exec(`CREATE TABLE t (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
		expires_at DATETIME NOT NULL,
		flag INTEGER NOT NULL DEFAULT 0,
		meta TEXT NULL
	)`); err != nil {
		t.Fatalf("create: %v", err)
	}

	want := time.Date(2026, 6, 17, 8, 30, 45, 123456000, time.UTC)
	if _, err := d.Exec(`INSERT INTO t (expires_at, flag, meta) VALUES (?, ?, ?)`,
		want, true, `{"k":"v"}`); err != nil {
		t.Fatalf("insert: %v", err)
	}

	var created, expires time.Time
	var flag bool
	var meta string
	if err := d.QueryRow(`SELECT created_at, expires_at, flag, meta FROM t WHERE id = 1`).
		Scan(&created, &expires, &flag, &meta); err != nil {
		t.Fatalf("scan: %v", err)
	}

	t.Logf("created=%v expires=%v flag=%v meta=%s", created, expires, flag, meta)
	if !expires.Equal(want) {
		t.Errorf("expires round-trip: got %v, want %v", expires.UTC(), want)
	}
	if created.IsZero() {
		t.Errorf("created_at default not populated")
	}
	if !flag || meta != `{"k":"v"}` {
		t.Errorf("flag/meta mismatch: flag=%v meta=%s", flag, meta)
	}

	// WHERE comparison against a time param (used by expires_at > ? queries).
	var n int
	if err := d.QueryRow(`SELECT COUNT(*) FROM t WHERE expires_at > ?`,
		want.Add(-time.Hour)).Scan(&n); err != nil {
		t.Fatalf("count: %v", err)
	}
	if n != 1 {
		t.Errorf("time comparison: got %d rows, want 1", n)
	}
}
