// Slice B.4 retirement of B.2 dual-write (t-paliad-305 / m/paliad#93).
//
// Mig 140 dropped paliad.deadline_rules and installed INSTEAD OF
// triggers on paliad.deadline_rules_unified that route writes to
// procedural_events + sequencing_rules + legal_sources. The legacy
// dual-write helper (syncDualWriteFromDeadlineRule) and the drift-check
// loop (CheckDualWriteDrift / StartDualWriteDriftCheckLoop) reference
// paliad.deadline_rules, which no longer exists — they would crash on
// first call if kept.
//
// Survivor: syncDeadlineProceduralEventID — keeps paliad.deadlines's
// new procedural_event_id column in sync with sequencing_rule_id after
// any UPDATE that touched the latter. Still useful as a "derive from
// canonical pointer" helper.
//
// The DualWriteDriftReport struct + HasDrift method are retired with
// the loop they served.

package services

import (
	"context"
	"fmt"

	"github.com/google/uuid"
	"github.com/jmoiron/sqlx"
)

// syncDeadlineProceduralEventID mirrors paliad.deadlines.sequencing_rule_id
// onto procedural_event_id. Call this within an open transaction AFTER
// any UPDATE that mutates paliad.deadlines.sequencing_rule_id (today's
// callers: DeadlineService.Update on the RuleSet branch, and the
// RuleEditorService orphan-resolve path which sets both columns in one
// statement so doesn't need this helper).
//
// Idempotent: NULL sequencing_rule_id collapses procedural_event_id to
// NULL via the subquery returning NULL. Slice B.4 (t-paliad-305).
func syncDeadlineProceduralEventID(ctx context.Context, tx *sqlx.Tx, deadlineID uuid.UUID) error {
	if _, err := tx.ExecContext(ctx, `
		UPDATE paliad.deadlines d
		   SET procedural_event_id = (
		           SELECT sr.procedural_event_id
		             FROM paliad.sequencing_rules sr
		            WHERE sr.id = d.sequencing_rule_id
		       )
		 WHERE d.id = $1`, deadlineID); err != nil {
		return fmt.Errorf("sync deadline procedural_event_id for %s: %w", deadlineID, err)
	}
	return nil
}
