package store

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/wangjia/pangolin/server/internal/db"
)

// Execer is satisfied by both *sql.DB and *sql.Tx.
type Execer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

// BumpDirectoryVersion atomically increments the directory_version singleton
// (the row is seeded by migration 7). This is the single canonical
// implementation; nodes.Lifecycle and the scheduler both call it instead of
// each carrying their own copy of the upsert.
func BumpDirectoryVersion(ctx context.Context, q Execer, d db.Dialect) error {
	_, err := q.ExecContext(ctx,
		`INSERT INTO directory_version (id, version) VALUES (1, 1) `+
			d.Upsert([]string{"id"}, "version = version + 1"))
	if err != nil {
		return fmt.Errorf("store.BumpDirectoryVersion: %w", err)
	}
	return nil
}
