package persistence

import (
	"context"
	"fmt"

	"github.com/nexuscrm/kernel/pkg/schema"
)

const (
	runtimePlatformCommandTable             = "_System_RuntimePlatformCommand"
	runtimePlatformCommandPartitionIndex    = "idx_runtime_platform_command_partition"
	runtimePlatformCommandPartitionIndexSQL = `ALTER TABLE _System_RuntimePlatformCommand
ADD INDEX idx_runtime_platform_command_partition (ExecutionScopeDigest, PartitionKey, State, LeaseExpiresAt, Id)`
)

var runtimePlatformCommandPartitionIndexColumns = []string{"ExecutionScopeDigest", "PartitionKey", "State", "LeaseExpiresAt", "Id"}

func declaresRuntimePlatformCommandPartitionIndex(def schema.TableDefinition) bool {
	if def.TableName != runtimePlatformCommandTable {
		return false
	}
	for _, index := range def.Indices {
		if index.Name == runtimePlatformCommandPartitionIndex {
			return !index.Primary && !index.Unique && equalExactColumnNames(index.Columns, runtimePlatformCommandPartitionIndexColumns)
		}
	}
	return false
}

// reconcileRuntimePlatformCommandPartitionIndex upgrades retained command
// inboxes before partition-aware workers become ready. CREATE TABLE IF NOT
// EXISTS cannot add the index to an existing table. Only the exact canonical
// declaration authorizes this additive migration; incompatible indexes remain
// untouched and fail closed rather than being dropped or silently accepted.
func (r *SchemaRepository) reconcileRuntimePlatformCommandPartitionIndex(ctx context.Context) error {
	columns, unique, hasPrefix, err := inspectManagedPhysicalIndex(
		ctx, r.db, runtimePlatformCommandTable, runtimePlatformCommandPartitionIndex,
	)
	if err != nil {
		return fmt.Errorf("reconcile runtime platform command partition index: %w", err)
	}
	if len(columns) != 0 {
		if !unique && !hasPrefix && equalExactColumnNames(columns, runtimePlatformCommandPartitionIndexColumns) {
			return nil
		}
		return fmt.Errorf(
			"reconcile runtime platform command partition index: physical %s.%s has incompatible shape (unique=%t, prefix=%t, columns=%v)",
			runtimePlatformCommandTable, runtimePlatformCommandPartitionIndex, unique, hasPrefix, columns,
		)
	}
	if _, err := r.db.ExecContext(ctx, runtimePlatformCommandPartitionIndexSQL); err != nil {
		return fmt.Errorf("reconcile runtime platform command partition index: add partition-scoped claim index: %w", err)
	}
	if err := VerifyExactTableIndex(
		ctx, r.db, runtimePlatformCommandTable, runtimePlatformCommandPartitionIndex,
		false, runtimePlatformCommandPartitionIndexColumns,
	); err != nil {
		return fmt.Errorf("reconcile runtime platform command partition index: verify migrated index: %w", err)
	}
	return nil
}
