USE [DevlDUTASJobSchedule]
GO
/****** Object:  StoredProcedure [dbo].[usp_ForceComplete]    Script Date: 10/4/2025 7:26:30 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/****** Merged Stored Procedure: Manual Override ******/
CREATE OR ALTER   PROCEDURE [dbo].[usp_ForceComplete]
    @JobName VARCHAR(50),
    @OperatorName VARCHAR(100)
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @Today DATE = CAST(GETDATE() AS DATE);

    -- Update existing job execution record if it exists
    UPDATE dbo.JobExecutionHistory 
    SET Status = 'ForceComplete',
        OverrideFlag = 1,
        OverrideBy = @OperatorName,
        OverrideDate = GETDATE(),
        ActualEndTime = GETDATE()
    WHERE JobName = @JobName 
        AND RunDate = @Today
        AND Status IN ('Failed', 'Running');

    -- If no row was updated, insert a new record
    IF @@ROWCOUNT = 0
    BEGIN
        INSERT INTO dbo.JobExecutionHistory (
            JobName, RunDate, ScheduledStartTime, Status, 
            OverrideFlag, OverrideBy, OverrideDate, ActualEndTime
        )
        SELECT 
            @JobName, @Today, ScheduledStartTime, 'ForceComplete',
            1, @OperatorName, GETDATE(), GETDATE()
        FROM dbo.JobControl 
        WHERE JobName = @JobName;
    END

    -- Provide feedback to the operator
    PRINT 'Job ' + @JobName + ' has been marked as forced complete by ' + @OperatorName;
END
