// Package catalogwriter owns the shared org-scoped Catalog writer row and its
// transaction primitives.
//
// The current durable column is named ActiveOperationId for compatibility with
// the already-deployed App authority schema. Its value is treated here as the
// active generic Catalog command identity. This package does not yet define a
// publication tuple, command journal, or serving selector.
package catalogwriter

import (
	"context"
	"database/sql"
)

var schemaStatements = []string{
	`CREATE TABLE IF NOT EXISTS _System_CatalogOrgState (
OrgId VARCHAR(255) PRIMARY KEY, RuntimeAudience VARCHAR(255) NOT NULL,
CatalogRevision DECIMAL(20,0) NOT NULL, LastSecurityEpoch DECIMAL(20,0) NOT NULL,
ActiveOperationId CHAR(36) NULL, WriterGeneration DECIMAL(20,0) NOT NULL DEFAULT 0,
CreatedDate DATETIME(6) NOT NULL, LastModifiedDate DATETIME(6) NOT NULL)`,
	`ALTER TABLE _System_CatalogOrgState
ADD COLUMN IF NOT EXISTS WriterGeneration DECIMAL(20,0) NOT NULL DEFAULT 0`,
}

// EnsureSchema creates the shared Catalog org-writer authority row. It does
// not create a publication selector. The additive WriterGeneration migration
// preserves existing lineage and initializes its first reservation fence at
// generation zero.
func EnsureSchema(ctx context.Context, db *sql.DB) error {
	for _, statement := range schemaStatements {
		if _, err := db.ExecContext(ctx, statement); err != nil {
			return err
		}
	}
	return nil
}

// SchemaStatementsForTest returns a defensive copy of the writer schema.
func SchemaStatementsForTest() []string {
	return append([]string(nil), schemaStatements...)
}
