package runtimeports

import (
	"context"
	"database/sql"

	"github.com/pingcap-inc/nexuscrm-contract/pkg/autonumberseed"
)

// AutoNumberSeeder is the composition seam for the autonumber cutover
// seed/verify operations that the control-plane apply paths invoke when
// installing or verifying autonumber-counter state from L0 + source-backed
// pack object-spec payloads.
//
// The concrete implementation (internal/bootstrap.AutoNumberSeederImpl)
// delegates each method to the canonical bootstrap function of the same name,
// so behavior is byte-for-byte identical to calling the bootstrap function
// directly. The port exists so that control-plane consumers
// (internal/controlplane/packs and internal/controlplane/tenantoverlay) depend
// on this neutral interface instead of importing internal/bootstrap for these
// writes. The concrete impl is wired at the runtime composition root
// (pkg/serverruntime).
//
// Method signatures MIRROR the bootstrap function signatures exactly — the
// seed/verify methods keep their ctx + *sql.DB arguments so the impl is
// STATELESS (no DB is bound at construction). The slice/key parameter types
// resolve to nexuscrm-contract/pkg/autonumberseed, which is the same pure-data
// package the bootstrap aliases (bootstrap.AutoNumberFormatSeed,
// bootstrap.AutoNumberDeclaredSeedKey) already point at, so callers can pass
// either alias unchanged. This package imports nothing backend-internal; like
// every symbol here it is interface-only and carries no behavior, DB access,
// or global state of its own.
type AutoNumberSeeder interface {
	// SeedAutoNumberCounters seeds the _System_AutoNumberCounter table from
	// live target-column data, legacy counter sources, and each field's
	// AutoNumberStart floor (scope-aware GREATEST). rawDB must be a connection
	// already serialized under the outer bootstrap mutation lock; the function
	// acquires no new GET_LOCK.
	SeedAutoNumberCounters(ctx context.Context, rawDB *sql.DB, seedMap []autonumberseed.AutoNumberFormatSeed, scopeSourceMap map[string]string) error

	// VerifyAutoNumberInvariants runs the full V1-V8 verify gate (including the
	// live-data V5/V7 scans) under the control-plane apply lock with writers
	// quiesced. Non-zero error blocks the apply/deploy.
	VerifyAutoNumberInvariants(ctx context.Context, rawDB *sql.DB) error

	// VerifyAutoNumberMetadataInvariants runs only the metadata-only gates
	// (V1, V2, V3, V4, V6, V8) that are safe on the hot pod-readiness path; the
	// live-data V5/V7 scans are deliberately skipped.
	VerifyAutoNumberMetadataInvariants(ctx context.Context, rawDB *sql.DB) error

	// RegisterAutoNumberDeclaredSeeds publishes the generated declared-seed
	// keys so the V8 cardinality floor can compute its declared-vs-reachable
	// expected count. Idempotent: repeated calls merge by declared key.
	RegisterAutoNumberDeclaredSeeds(keys []autonumberseed.AutoNumberDeclaredSeedKey)
}
