SET QUOTED_IDENTIFIER ON

GO

-- ============================================================================
-- Trend Display — speed up TrackBilletInStands so the visualizer identifies
-- billets in (near) real time.
--
-- Measured durations (sys.dm_exec_procedure_stats, 2026-05-12):
--   TrackBilletInStands  avg 55 ms, max 264 ms.
-- Margin at 5 s period   = 5000 / 264 ≈ 19×, CPU load = ~1.1 %.
-- See docs/production/trend-display/REAL-TIME-BILLET-TRACKING-PLAN.md.
-- ============================================================================
UPDATE [SYSTEM].catJobs
SET PeriodTime = 5
WHERE sProcedure = '[MILL].[TrackBilletInStands]'
  AND PeriodTime <> 5;
GO

-- ============================================================================
-- Delays tracking — disable the legacy jobs and register the new MILL.TrackDelays
-- ============================================================================

-- Disable the 3 legacy delay jobs (replaced by [MILL].[TrackDelays]).
UPDATE [SYSTEM].catJobs
SET Enabled = 0
WHERE sProcedure IN (
    '[RBD].[SyncDelaysJob]',
    '[RBD].[TrackDelaysJob_OldHistorian]',
    '[RBD].[TrackDelaysJob_NewHistorian]'
);
GO

-- Register [MILL].[TrackDelays] idempotently (UpsertJob with @JobId=NULL
-- always inserts, so guard with IF NOT EXISTS to avoid duplicates on republish).
IF NOT EXISTS (
    SELECT 1 FROM [SYSTEM].catJobs WHERE sProcedure = '[MILL].[TrackDelays]'
)
BEGIN
    EXEC [SYSTEM].[UpsertJob]
        @sProcedure          = '[MILL].[TrackDelays]',
        @StartTime           = '2026-01-01 00:00:00',
        @PeriodTime          = 5,
        @RestartAfterFailure = 1,
        @User                = 'devops';
END
GO

-- CRITICAL: UpsertJob does NOT set NextExecutionTime → without this the
-- JobManager never picks the job up. Trigger the first run now.
UPDATE [SYSTEM].catJobs
SET NextExecutionTime = GETUTCDATE()
WHERE sProcedure = '[MILL].[TrackDelays]'
  AND (NextExecutionTime IS NULL OR NextExecutionTime > GETUTCDATE());
GO
