package store

import (
	"os"
	"testing"
)

func TestOpen(t *testing.T) {
	// Create a temporary database
	dbPath := "/tmp/test_fetchml.db"
	defer os.Remove(dbPath)
	defer os.Remove(dbPath + "-wal")
	defer os.Remove(dbPath + "-shm")

	store, err := Open(dbPath)
	if err != nil {
		t.Fatalf("Failed to open database: %v", err)
	}
	defer store.Close()

	if store.db == nil {
		t.Fatal("Database connection is nil")
	}

	if store.dbPath != dbPath {
		t.Fatalf("Expected dbPath %s, got %s", dbPath, store.dbPath)
	}
}

func TestGetUnsyncedRuns(t *testing.T) {
	dbPath := "/tmp/test_fetchml_unsynced.db"
	defer os.Remove(dbPath)
	defer os.Remove(dbPath + "-wal")
	defer os.Remove(dbPath + "-shm")

	store, err := Open(dbPath)
	if err != nil {
		t.Fatalf("Failed to open database: %v", err)
	}
	defer store.Close()

	// Insert test data
	_, err = store.db.Exec(`
		INSERT INTO ml_experiments (experiment_id, name) VALUES ('exp1', 'Test Experiment');
	`)
	if err != nil {
		t.Fatalf("Failed to insert experiment: %v", err)
	}

	_, err = store.db.Exec(`
		INSERT INTO ml_runs (run_id, experiment_id, name, status, synced) 
		VALUES ('run1', 'exp1', 'Test Run', 'FINISHED', 0);
	`)
	if err != nil {
		t.Fatalf("Failed to insert run: %v", err)
	}

	// Test GetUnsyncedRuns
	runs, err := store.GetUnsyncedRuns()
	if err != nil {
		t.Fatalf("Failed to get unsynced runs: %v", err)
	}

	if len(runs) != 1 {
		t.Fatalf("Expected 1 unsynced run, got %d", len(runs))
	}

	if runs[0].RunID != "run1" {
		t.Fatalf("Expected run_id 'run1', got '%s'", runs[0].RunID)
	}
}

func TestMarkRunSynced(t *testing.T) {
	dbPath := "/tmp/test_fetchml_sync.db"
	defer os.Remove(dbPath)
	defer os.Remove(dbPath + "-wal")
	defer os.Remove(dbPath + "-shm")

	store, err := Open(dbPath)
	if err != nil {
		t.Fatalf("Failed to open database: %v", err)
	}
	defer store.Close()

	// Insert test data
	_, err = store.db.Exec(`
		INSERT INTO ml_experiments (experiment_id, name) VALUES ('exp1', 'Test Experiment');
	`)
	if err != nil {
		t.Fatalf("Failed to insert experiment: %v", err)
	}

	_, err = store.db.Exec(`
		INSERT INTO ml_runs (run_id, experiment_id, name, status, synced) 
		VALUES ('run1', 'exp1', 'Test Run', 'FINISHED', 0);
	`)
	if err != nil {
		t.Fatalf("Failed to insert run: %v", err)
	}

	// Mark as synced
	err = store.MarkRunSynced("run1")
	if err != nil {
		t.Fatalf("Failed to mark run as synced: %v", err)
	}

	// Verify
	var synced int
	err = store.db.QueryRow("SELECT synced FROM ml_runs WHERE run_id = 'run1'").Scan(&synced)
	if err != nil {
		t.Fatalf("Failed to query run: %v", err)
	}

	if synced != 1 {
		t.Fatalf("Expected synced=1, got %d", synced)
	}
}
