-- ============================================================================
-- PHASE 3: Performance Indexes for Monitoring & Observability
-- ============================================================================

-- Index for approval metrics queries (failure monitoring)
CREATE INDEX IF NOT EXISTS idx_approval_metrics_failures 
  ON approval_transaction_metrics(success, created_at DESC) 
  WHERE success = false;

-- Index for approval metrics with moderator lookup
CREATE INDEX IF NOT EXISTS idx_approval_metrics_moderator 
  ON approval_transaction_metrics(moderator_id, created_at DESC);

-- Composite index for submission item status queries
CREATE INDEX IF NOT EXISTS idx_submission_items_status_submission 
  ON submission_items(status, submission_id) 
  WHERE status IN ('pending', 'approved', 'rejected');

-- Index for submission items with pending status (fast filtering)
CREATE INDEX IF NOT EXISTS idx_submission_items_pending 
  ON submission_items(submission_id) 
  WHERE status = 'pending';

-- Index for idempotency key lookups (fast duplicate detection)
CREATE INDEX IF NOT EXISTS idx_idempotency_keys_status 
  ON submission_idempotency_keys(idempotency_key, status, created_at DESC);

-- Add comments for documentation
COMMENT ON INDEX idx_approval_metrics_failures IS 'Optimizes approval failure monitoring queries';
COMMENT ON INDEX idx_approval_metrics_moderator IS 'Speeds up per-moderator approval stats';
COMMENT ON INDEX idx_submission_items_status_submission IS 'Optimizes submission item status filtering';
COMMENT ON INDEX idx_submission_items_pending IS 'Fast lookup for pending items in a submission';
COMMENT ON INDEX idx_idempotency_keys_status IS 'Optimizes duplicate request detection';