package core

import (
	"testing"
)

func TestTestDBSeed(t *testing.T) {
	schema := `CREATE TABLE products (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, price REAL NOT NULL);`

	t.Run("inserta una fila correctamente", func(t *testing.T) {
		tdb := TestDBSetup(t, schema)

		err := TestDBSeed(t, tdb.DB, "products", []map[string]any{
			{"name": "Widget", "price": 9.99},
		})
		if err != nil {
			t.Fatalf("seed: %v", err)
		}

		var count int
		if err := tdb.DB.QueryRow(`SELECT COUNT(*) FROM products`).Scan(&count); err != nil {
			t.Fatalf("count: %v", err)
		}
		if count != 1 {
			t.Errorf("got %d rows, want 1", count)
		}
	})

	t.Run("inserta multiples filas en una transaccion", func(t *testing.T) {
		tdb := TestDBSetup(t, schema)

		rows := []map[string]any{
			{"name": "A", "price": 1.0},
			{"name": "B", "price": 2.0},
			{"name": "C", "price": 3.0},
		}
		err := TestDBSeed(t, tdb.DB, "products", rows)
		if err != nil {
			t.Fatalf("seed: %v", err)
		}

		var count int
		if err := tdb.DB.QueryRow(`SELECT COUNT(*) FROM products`).Scan(&count); err != nil {
			t.Fatalf("count: %v", err)
		}
		if count != 3 {
			t.Errorf("got %d rows, want 3", count)
		}
	})

	t.Run("slice vacio no hace nada y retorna nil", func(t *testing.T) {
		tdb := TestDBSetup(t, schema)

		err := TestDBSeed(t, tdb.DB, "products", []map[string]any{})
		if err != nil {
			t.Errorf("expected nil for empty rows, got: %v", err)
		}

		var count int
		if err := tdb.DB.QueryRow(`SELECT COUNT(*) FROM products`).Scan(&count); err != nil {
			t.Fatalf("count: %v", err)
		}
		if count != 0 {
			t.Errorf("got %d rows, want 0", count)
		}
	})

	t.Run("error en tabla inexistente retorna error", func(t *testing.T) {
		tdb := TestDBSetup(t, schema)

		err := TestDBSeed(t, tdb.DB, "nonexistent_table", []map[string]any{
			{"name": "X", "price": 1.0},
		})
		if err == nil {
			t.Error("expected error for nonexistent table, got nil")
		}
	})
}
