package persistence

import (
	"context"
	"fmt"

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

const (
	runtimeOutboundIntentOwnerTable    = "_System_RuntimeOutboundIntent"
	runtimeOutboundIntentOwnerIndex    = "idx_runtime_outbound_intent_owner"
	runtimeOutboundIntentOwnerIndexSQL = `ALTER TABLE _System_RuntimeOutboundIntent
ADD INDEX idx_runtime_outbound_intent_owner (SourceObject, SourceRecordId, AdmissionState)`
)

var runtimeOutboundIntentOwnerIndexColumns = []string{"SourceObject", "SourceRecordId", "AdmissionState"}

func declaresRuntimeOutboundIntentOwnerIndex(def schema.TableDefinition) bool {
	if def.TableName != runtimeOutboundIntentOwnerTable {
		return false
	}
	for _, index := range def.Indices {
		if index.Name == runtimeOutboundIntentOwnerIndex {
			return !index.Primary && !index.Unique && equalExactColumnNames(index.Columns, runtimeOutboundIntentOwnerIndexColumns)
		}
	}
	return false
}

// reconcileRuntimeOutboundIntentOwnerIndex adds the canonical owner-leading
// lookup to retained intent inboxes. It never rewrites a conflicting physical
// index, and cannot let a worker become ready without the bounded owner lookup.
func (r *SchemaRepository) reconcileRuntimeOutboundIntentOwnerIndex(ctx context.Context) error {
	columns, unique, hasPrefix, err := inspectManagedPhysicalIndex(ctx, r.db, runtimeOutboundIntentOwnerTable, runtimeOutboundIntentOwnerIndex)
	if err != nil {
		return fmt.Errorf("reconcile runtime outbound intent owner index: %w", err)
	}
	if len(columns) != 0 {
		if !unique && !hasPrefix && equalExactColumnNames(columns, runtimeOutboundIntentOwnerIndexColumns) {
			return nil
		}
		return fmt.Errorf("reconcile runtime outbound intent owner index: physical %s.%s has incompatible shape (unique=%t, prefix=%t, columns=%v)",
			runtimeOutboundIntentOwnerTable, runtimeOutboundIntentOwnerIndex, unique, hasPrefix, columns)
	}
	if _, err := r.db.ExecContext(ctx, runtimeOutboundIntentOwnerIndexSQL); err != nil {
		return fmt.Errorf("reconcile runtime outbound intent owner index: add owner lookup: %w", err)
	}
	if err := VerifyExactTableIndex(ctx, r.db, runtimeOutboundIntentOwnerTable, runtimeOutboundIntentOwnerIndex, false, runtimeOutboundIntentOwnerIndexColumns); err != nil {
		return fmt.Errorf("reconcile runtime outbound intent owner index: verify migrated index: %w", err)
	}
	return nil
}
