package postgres

import (
	"context"
	"database/sql"
)

// ExtDataStore implements store.ExtDataStore for Postgres.
type ExtDataStore struct {
	db *sql.DB
}

func NewExtDataStore(db *sql.DB) *ExtDataStore {
	return &ExtDataStore{db: db}
}

func (s *ExtDataStore) RegisterTable(ctx context.Context, packageID, tableName string) error {
	_, err := s.db.ExecContext(ctx,
		`INSERT INTO ext_data_tables (package_id, table_name)
		 VALUES ($1, $2)
		 ON CONFLICT (package_id, table_name) DO NOTHING`,
		packageID, tableName)
	return err
}

func (s *ExtDataStore) ListTables(ctx context.Context, packageID string) ([]string, error) {
	rows, err := s.db.QueryContext(ctx,
		`SELECT table_name FROM ext_data_tables
		 WHERE package_id = $1
		 ORDER BY table_name`,
		packageID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var names []string
	for rows.Next() {
		var n string
		if err := rows.Scan(&n); err != nil {
			return nil, err
		}
		names = append(names, n)
	}
	if names == nil {
		names = []string{}
	}
	return names, nil
}

func (s *ExtDataStore) DeletePackageTables(ctx context.Context, packageID string) error {
	_, err := s.db.ExecContext(ctx,
		`DELETE FROM ext_data_tables WHERE package_id = $1`, packageID)
	return err
}
