﻿

-- Example usage:  EXEC dbo.usp_BackupAndClearInvoiceFile @InvoiceID = 'R2025-0057';

CREATE   PROCEDURE [dbo].[_BackupAndClearInvoiceFile]
    @InvoiceID nvarchar(25)
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @invID varchar(10);
    DECLARE @today datetime;
    DECLARE @td nvarchar(max);
    DECLARE @sql nvarchar(max) = '';
    DECLARE @ErrorMessage nvarchar(500);
    
    -- Get the invoice ID
    SELECT TOP(1) @invID = [id] 
    FROM dbo.fds__invoices 
    WHERE InvoiceId = @InvoiceID;
    
    -- Check if invoice exists
    IF ISNULL(@invID, '') = ''
    BEGIN
        SET @ErrorMessage = 'Invoice not found: ' + @InvoiceID;
        PRINT @ErrorMessage;
        RETURN -1;
    END
    
    -- Generate backup table prefix with timestamp
    SET @today = GETDATE();
    SET @td = FORMAT(@today, 'yyyy-MM-dd_HHmm');
    
    PRINT 'Backup table prefix: ' + @td;
    
    BEGIN TRY
        -- Build dynamic SQL for backup and update
        SET @sql = @sql + N'SELECT * INTO [' + @td + ' fds__invoices] FROM dbo.fds__invoices WHERE Id = ''' + CAST(@invID as nvarchar(max)) + ''';';
        SET @sql = @sql + N'SELECT * INTO [' + @td + ' fds__invoice_items] FROM dbo.fds__invoice_items WHERE InvId = ''' + CAST(@invID as nvarchar(max)) + ''';';
        SET @sql = @sql + N'SELECT * INTO [' + @td + ' fds__invoice_details] FROM dbo.fds__invoice_details WHERE InvId = ''' + CAST(@invID as nvarchar(max)) + ''';';
        
        -- Clear file column after successful backup
        SET @sql = @sql + N'IF EXISTS (SELECT 1 FROM [dbo].[' + @td + ' fds__invoices]) 
                                BEGIN
                                    UPDATE dbo.fds__invoices SET [file] = NULL WHERE [Id] = ''' + CAST(@invID as nvarchar(max)) + ''';
                                END;';
        
        -- Execute the dynamic SQL
        EXEC sp_executesql @sql;
        
        PRINT 'SUCCESS: Backup created and file column cleared for Invoice: ' + @InvoiceID;

        

    Print Formatmessage('https://sanitaerfuchs.de/intranet/do/req/idoc?id=%s&create=1', @invID);
    Print Formatmessage('https://sanitaerfuchs.de/intranet/do/inv/rdoc?id=%s&create=1', @invID);


        RETURN 0;
        
    END TRY
    BEGIN CATCH
        SET @ErrorMessage = 'ERROR: ' + ERROR_MESSAGE();
        PRINT @ErrorMessage;
        RETURN -1;
    END CATCH

END