-- T3-MultiSourceSummary
DECLARE @JustForDebug TINYINT = 0;

-- SETUP VARIABLES
DECLARE @Number INT = (SELECT COUNT(id) + 1  FROM [diunabi-morska].[dbo].[Layers]);
DECLARE @CurrentTimestamp NVARCHAR(14) = FORMAT(GETDATE(), 'yyyyMMddHHmm');
DECLARE @Name NVARCHAR(50) = CONCAT(
    'L', @Number, '-A-C_D3-', @CurrentTimestamp
);
DECLARE @LayerId UNIQUEIDENTIFIER = NEWID();

DECLARE @Query NVARCHAR(MAX) = '
    SELECT
    REPLACE(dko_Konto, ''-'', '''') + 
    CAST(YEAR(dko_DataDekretacji) AS VARCHAR) + 
    RIGHT(''0'' + CAST(MONTH(dko_DataDekretacji) AS VARCHAR), 2) AS Code,
    SUM(dko_KwotaWn) AS Value
FROM [PRZYCHODNIA_MORSKA_SP_ZOO].[dbo].[dkr_Pozycja]
WHERE dko_Konto = ''402-5'' AND YEAR(dko_DataDekretacji) > 2023
GROUP BY dko_Konto, dko_DataDekretacji ,dko_DataDekretacji
ORDER BY dko_Konto, dko_DataDekretacji;
';

SELECT @Name AS Name, @Query AS Query;

IF @JustForDebug = 1
BEGIN
    SELECT 'Just for debug' AS Logger;
    RETURN;
END;

INSERT INTO [diunabi-morska].[dbo].[Layers]
([Id], [Number], [Name], [CreatedAt], [ModifiedAt], [IsDeleted], [CreatedById], [ModifiedById], [Type])
VALUES (@LayerId, @Number, @Name, GETDATE(), GETDATE(), 0, '117be4f0-b5d1-41a1-a962-39dc30cce368', '117be4f0-b5d1-41a1-a962-39dc30cce368', 2);

INSERT INTO [diunabi-morska].[dbo].[Records]
([Id], [Code], [Desc1], [CreatedAt], [ModifiedAt], [CreatedById], [ModifiedById], [IsDeleted], [LayerId])
VALUES ((SELECT NEWID()), 'Type', 'ExternalConfiguration', GETDATE(), GETDATE(), '117be4f0-b5d1-41a1-a962-39dc30cce368', '117be4f0-b5d1-41a1-a962-39dc30cce368', 0, @LayerId);

INSERT INTO [diunabi-morska].[dbo].[Records]
([Id], [Code], [Desc1], [CreatedAt], [ModifiedAt], [CreatedById], [ModifiedById], [IsDeleted], [LayerId])
VALUES ((SELECT NEWID()), 'ConfigurationType', 'D3', GETDATE(), GETDATE(), '117be4f0-b5d1-41a1-a962-39dc30cce368', '117be4f0-b5d1-41a1-a962-39dc30cce368', 0, @LayerId);

INSERT INTO [diunabi-morska].[dbo].[Records]
([Id], [Code], [Desc1], [CreatedAt], [ModifiedAt], [CreatedById], [ModifiedById], [IsDeleted], [LayerId])
VALUES ((SELECT NEWID()), 'IsEnabled', 'True', GETDATE(), GETDATE(), '117be4f0-b5d1-41a1-a962-39dc30cce368', '117be4f0-b5d1-41a1-a962-39dc30cce368', 0, @LayerId);

INSERT INTO [diunabi-morska].[dbo].[Records]
([Id], [Code], [Desc1], [CreatedAt], [ModifiedAt], [CreatedById], [ModifiedById], [IsDeleted], [LayerId])
VALUES ((SELECT NEWID()), 'SQL-QUERY-1', @Query, GETDATE(), GETDATE(), '117be4f0-b5d1-41a1-a962-39dc30cce368', '117be4f0-b5d1-41a1-a962-39dc30cce368', 0, @LayerId);