package service

import (
	"os"
	"testing"

	"github.com/seifghazi/claude-code-monitor/internal/config"
)

func TestPostgresStorageContract(t *testing.T) {
	dsn := os.Getenv("TEST_POSTGRES_DSN")
	if dsn == "" {
		t.Skip("TEST_POSTGRES_DSN not set")
	}

	runStorageContractTests(t, storageFactory{
		name: "postgres",
		new: func(t *testing.T, cfg config.StorageConfig) StorageService {
			t.Helper()
			cfg.DBType = "postgres"
			cfg.DatabaseURL = dsn
			return newTestPostgresStorage(t, cfg)
		},
	})
}

func newTestPostgresStorage(t *testing.T, cfg config.StorageConfig) *postgresStorageService {
	t.Helper()

	storage, err := NewPostgresStorageService(&cfg)
	if err != nil {
		t.Fatalf("NewPostgresStorageService() error = %v", err)
	}

	pgStorage, ok := storage.(*postgresStorageService)
	if !ok {
		t.Fatalf("unexpected storage type %T", storage)
	}

	resetPostgresTestStorage(t, pgStorage)
	t.Cleanup(func() {
		resetPostgresTestStorage(t, pgStorage)
		if err := pgStorage.Close(); err != nil {
			t.Errorf("Close() error = %v", err)
		}
	})

	return pgStorage
}

func resetPostgresTestStorage(t *testing.T, storage *postgresStorageService) {
	t.Helper()

	if _, err := storage.db.Exec("TRUNCATE TABLE requests"); err != nil {
		t.Fatalf("TRUNCATE requests error = %v", err)
	}
	if _, err := storage.db.Exec("DELETE FROM settings"); err != nil {
		t.Fatalf("DELETE settings error = %v", err)
	}
}
