SET QUOTED_IDENTIFIER ON
GO

-- IsHeatIdManual Default
-- Check if the default constraint exists
IF NOT EXISTS (
    SELECT 1
    FROM sys.default_constraints dc
    INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id
    WHERE c.name = 'IsHeatIdManual'
      AND OBJECT_NAME(dc.parent_object_id) = 'Processes'
)
BEGIN
    -- Remove any inline default constraint (if necessary)
    ALTER TABLE [MS].[Processes]
    ALTER COLUMN [IsHeatIdManual] BIT NOT NULL;

    -- Add the named default constraint
    ALTER TABLE [MS].[Processes]
    ADD CONSTRAINT [DF_Processes_IsHeatIdManual]
    DEFAULT ((0)) FOR [IsHeatIdManual];
END
      

-- Insert configuration settings for SWV.CreateScheduledHeatsJob

  INSERT INTO [UTL].[catSettings] ([SettingName], [Value], [Description])
  VALUES
  (
      'SWV_CREATE_SCHEDULED_HEATS_TARGET_PER_EAF',
      '2',
      'CreateScheduledHeatsJob: Number of scheduled heats (status=S) to maintain per EAF furnace. Job creates new heats when count falls below this target.'
  ),
  (
      'SWV_CREATE_SCHEDULED_HEATS_FF_FILL_GAPS_MODE',
      '1',
      'CreateScheduledHeatsJob: When ON, creates consecutive heat numbers from last non-scheduled heat (e.g., 217→218→219). When OFF, continues from last created scheduled heat (e.g.,
  217, 219→220).'
  ),
  (
      'SWV_CREATE_SCHEDULED_HEATS_TIME_WINDOW_HOURS',
      '48',
      'CreateScheduledHeatsJob: Time window in hours to search for recent heats when determining reference heat and counting scheduled heats. Prevents wrap-around issues (e.g., ignores
   March 29999 when working in November 24000 range).'
  );


-- Register SWV.CreateScheduledHeatsJob in SYSTEM.catJobs
  INSERT INTO [SYSTEM].[catJobs] (
      [sProcedure],
      [RestartAfterFailure],
      [PeriodTime],
      [StartTime],
      [Enabled],
      [CurrentStatus]
  )
  VALUES (
      'SWV.CreateScheduledHeatsJob',  -- Stored procedure name
      1,                               -- RestartAfterFailure = Yes
      1800,                            -- PeriodTime = 1800 seconds (30 minutes)
      GETUTCDATE(),                    -- StartTime = Now
      1,                               -- Enabled = Yes
      'P'                              -- CurrentStatus = Pending
  );

  -- Verify the job was registered
  SELECT *
  FROM [SYSTEM].[catJobs]
  WHERE sProcedure = 'SWV.CreateScheduledHeatsJob';
