SET QUOTED_IDENTIFIER ON

GO

-- ============================================================
-- Forecast Data Entry (2026-05-27)
-- ============================================================

-- Per-page revamp flag (default '0' = legacy until cutover).
-- Shared by GetMonthlyEstimationProxy + GetForecastReportProxy.
-- UTL.SetSetting signature: (@OldName, @NewName, @Value, @Description=NULL)
IF NOT EXISTS (SELECT 1 FROM UTL.catSettings WHERE SettingName = 'Mill.DBRevampEnabled.ForecastDataEntry')
    EXEC UTL.SetSetting
        @OldName     = 'Mill.DBRevampEnabled.ForecastDataEntry',
        @NewName     = 'Mill.DBRevampEnabled.ForecastDataEntry',
        @Value       = '0',
        @Description = 'Per-page revamp flag for Forecast Data Entry. Flip to ''1'' after parity verification.';
GO

-- SP permissions (frontend-callable SPs only — the sync job is invoked by
-- JobManager, not by the API, so it is not registered in SEC)
EXEC SEC.UpsertProcedureAndSetToProfile 'SAL.GetMonthlyEstimation',      'Admin Profile', 'admin';
EXEC SEC.UpsertProcedureAndSetToProfile 'SAL.GetMonthlyEstimationProxy', 'Admin Profile', 'admin';
EXEC SEC.UpsertProcedureAndSetToProfile 'SAL.GetForecastReport',         'Admin Profile', 'admin';
EXEC SEC.UpsertProcedureAndSetToProfile 'SAL.GetForecastReportProxy',    'Admin Profile', 'admin';
EXEC SEC.UpsertProcedureAndSetToProfile 'SAL.UpdateMonthlyData',         'Admin Profile', 'admin';
GO

-- Register RBD.SyncMonthlyEstimationsJob in SYSTEM.catJobs.
-- PeriodTime = 600 seconds (10 min) — forecasts are entered manually, low
-- frequency. Pair with UPDATE to set NextExecutionTime and Enabled so the
-- worker picks it up on the very next tick after deploy.
-- Per [[feedback_register_job_complete]] / [[feedback_upsertjob_next_execution]]:
--   UpsertJob does NOT set NextExecutionTime nor Enabled. Use GETDATE() (local),
--   not GETUTCDATE() — JobManager Worker compares against DateTime.Now.
IF NOT EXISTS (SELECT 1 FROM SYSTEM.catJobs WHERE sProcedure = 'RBD.SyncMonthlyEstimationsJob')
BEGIN
    EXEC SYSTEM.UpsertJob
        @JobId               = NULL,
        @sProcedure          = 'RBD.SyncMonthlyEstimationsJob',
        @StartTime           = NULL,
        @PeriodTime          = 600,
        @RestartAfterFailure = 1,
        @User                = 'devops';

    UPDATE SYSTEM.catJobs
       SET NextExecutionTime = GETDATE(),
           Enabled           = 1
     WHERE sProcedure = 'RBD.SyncMonthlyEstimationsJob';
END
GO
