package sqlite

import "context"

// ExtDataStore implements store.ExtDataStore for SQLite.
type ExtDataStore struct{}

func NewExtDataStore() *ExtDataStore {
	return &ExtDataStore{}
}

func (s *ExtDataStore) RegisterTable(ctx context.Context, packageID, tableName string) error {
	_, err := DB.ExecContext(ctx,
		`INSERT OR IGNORE INTO ext_data_tables (package_id, table_name)
		 VALUES (?, ?)`,
		packageID, tableName)
	return err
}

func (s *ExtDataStore) ListTables(ctx context.Context, packageID string) ([]string, error) {
	rows, err := DB.QueryContext(ctx,
		`SELECT table_name FROM ext_data_tables
		 WHERE package_id = ?
		 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 := DB.ExecContext(ctx,
		`DELETE FROM ext_data_tables WHERE package_id = ?`, packageID)
	return err
}
