SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Bruno Pessanha
-- Create date: 23/10/2017
-- Description:	Create an invoice
-- Isuse:		RPKI-188
-- =============================================
CREATE PROCEDURE dbo.spCreateInvoice
	@Id UNIQUEIDENTIFIER,
	@UserId NVARCHAR(128),
	@MaxDate DATETIME
AS
BEGIN
	SET NOCOUNT ON;

	INSERT INTO [dbo].[Invoices] ([Id], [UserId], [MaxDateUtc], [DateCreatedUtc])
	VALUES (@Id, @UserId, @MaxDate, GETUTCDATE())

	UPDATE dbo.[ApiTransactions] 
	SET InvoiceId = @Id 
	WHERE InvoiceId IS NULL AND UserId = @UserId AND DateUtc < @MaxDate
END
GO

-- =============================================
-- Author:		Bruno Pessanha
-- Create date: 24/10/2017
-- Description:	Delete an invoice
-- Isuse:		RPKI-188
-- =============================================
CREATE PROCEDURE dbo.spDeleteInvoice
	-- Add the parameters for the stored procedure here
	@Id UNIQUEIDENTIFIER
AS
BEGIN
	SET NOCOUNT ON;

	UPDATE dbo.[ApiTransactions] 
	SET InvoiceId = NULL
	WHERE InvoiceId = @Id

	DELETE dbo.[Invoices] WHERE ID = @Id

END
GO
