package e2eutil

import (
	"fmt"
	"os"

	"github.com/jmoiron/sqlx"

	// register drivers with package to avoid a possible unknown driver error on cleanup
	_ "github.com/lib/pq"
)

const truncate = `
TRUNCATE TABLE accounts CASCADE;
TRUNCATE TABLE event_streams CASCADE;
TRUNCATE TABLE event_types CASCADE;
TRUNCATE TABLE aws_leases CASCADE;
TRUNCATE TABLE publications CASCADE;
TRUNCATE TABLE services CASCADE;
TRUNCATE TABLE subscription_targets CASCADE;
TRUNCATE TABLE subscriptions CASCADE;
`

func TruncateDB() error {
	username := os.Getenv("POSTGRES_WRITER_USER")
	password := os.Getenv("POSTGRES_WRITER_PASSWORD")
	host := os.Getenv("POSTGRES_WRITER_HOST")
	db := os.Getenv("POSTGRES_DB")
	connString := fmt.Sprintf("postgres://%s:%s@%s:5432/%s?sslmode=disable", username, password, host, db)
	writerDB, err := sqlx.Connect("postgres", connString)
	if err != nil {
		return err
	}
	_, err = writerDB.Exec(truncate)

	return err
}

// LocalDBSecretsClient is used to bootstrap a connection to a local Postgres container
// for running E2E tests against
type LocalDBSecretsClient struct{}

func (c *LocalDBSecretsClient) PostgresUsername() (string, error) {
	return os.Getenv("POSTGRES_WRITER_USER"), nil
}
func (c *LocalDBSecretsClient) PostgresPassword() (string, error) {
	return os.Getenv("POSTGRES_WRITER_PASSWORD"), nil
}
func (c *LocalDBSecretsClient) PostgresReaderUsername() (string, error) {
	return os.Getenv("POSTGRES_WRITER_USER"), nil
}
func (c *LocalDBSecretsClient) PostgresReaderPassword() (string, error) {
	return os.Getenv("POSTGRES_WRITER_PASSWORD"), nil
}
