MERGE [dbo].[MarketplaceListingReviews] AS Target
    USING (VALUES (@Id,
    @TenantId,
    @ListingId,
    @ListingName,
    @ListingSlug,
    @ListingSummary,
    @SubmissionNotes,
    @SubmittedBy,
    @SubmittedAtUtc))
    AS Source (Id,
    TenantId,
    ListingId,
    ListingName,
    ListingSlug,
    ListingSummary,
    SubmissionNotes,
    SubmittedBy,
    SubmittedAtUtc)
    ON Target.[TenantId] = Source.TenantId
    AND Target.[ListingId] = Source.ListingId
    AND Target.[Status] = 0 -- Pending
    WHEN MATCHED THEN
UPDATE
    SET [ListingName] = Source.ListingName,
    [ListingSlug] = Source.ListingSlug,
    [ListingSummary] = Source.ListingSummary,
    [SubmissionNotes] = Source.SubmissionNotes,
    [SubmittedBy] = Source.SubmittedBy,
    [SubmittedAtUtc] = Source.SubmittedAtUtc,
    [ReviewerEmail] = NULL,
    [ReviewerNotes] = NULL,
    [ResolvedAtUtc] = NULL,
    [UpdatedAtUtc] = SYSUTCDATETIME()
    WHEN NOT MATCHED THEN
INSERT
(
[Id],
[TenantId],
[ListingId],
[ListingName],
[ListingSlug],
[ListingSummary],
[SubmissionNotes],
[SubmittedBy],
[SubmittedAtUtc],
[Status],
[ReviewerEmail],
[ReviewerNotes],
[CreatedAtUtc],
[UpdatedAtUtc])
VALUES (COALESCE (NULLIF (Source.Id, '00000000-0000-0000-0000-000000000000'), NEWID()), Source.TenantId, Source.ListingId, Source.ListingName, Source.ListingSlug, Source.ListingSummary, Source.SubmissionNotes, Source.SubmittedBy, Source.SubmittedAtUtc, 0, -- Pending
    NULL, NULL, SYSUTCDATETIME(), SYSUTCDATETIME())
    OUTPUT inserted.*;
