--[[----------------------------------------------------------------------------

LrWatermarkIndexDefinitions.lua

--------------------------------------------------------------------------------

ADOBE CONFIDENTIAL
------------------
Copyright 2020 Adobe Inc.
All Rights Reserved.

NOTICE: All information contained herein is, and remains the property of
Adobe Systems Incorporated and its suppliers, if any. The intellectual and
technical concepts contained herein are proprietary to Adobe Systems
Incorporated and its suppliers and are protected by all applicable
intellectual property laws, including trade secret and copyright laws.
Dissemination of this information or reproduction of this material is
strictly forbidden unless prior written permission is obtained from
Adobe Systems Incorporated.

----------------------------------------------------------------------------]]--

local WFArguments = require 'WFArguments'
local KSTableUtils = require 'KSTableUtils'
--------------------------------------------------------------------------------

local check = assert( WFArguments.check )
local derefOpt = KSTableUtils.derefOpt

--============================================================================--

-- @mark LrCommentsIndexDefinitions namespace

local LrWatermarkIndexDefinitions = {}

--------------------------------------------------------------------------------

function LrWatermarkIndexDefinitions.generateIndexSchema( indexStoreSchema )

	check( 'WFRxIndexStoreSchema' )

	-- table watermark
	indexStoreSchema:addTable {

		sql = [[CREATE TABLE watermark( created, name, updated )]],

		relevantTypeSubtypeTuples = {
			{ 'watermark', 'text' }
		},

		map = function( docValue, emit )

			if docValue and not docValue._deleted and docValue.type == 'watermark' then

				local OzCreated = derefOpt( docValue, '_serverProvidedMetadata', 'created' )
				local OzUpdated = derefOpt( docValue, '_serverProvidedMetadata', 'updated' )

				-- Default watermark shall be the one that first hits the Oz
				-- Hence OzCreated prefered first here over userCreated
				local created = OzCreated or docValue.userCreated

				-- userUpdated filed not mandatory and hence default to Ozupdated if not exist
				local updated = docValue.userUpdated or OzUpdated

				local name = docValue.displayName

				if created and name and updated then
					emit( created, name, updated )
				end

			end

		end,
		useLocalId = false,
		hasOneRowPerDocument = true,

	}

	indexStoreSchema:addIndex [[CREATE INDEX watermark_name ON watermark( name )]]
	
end

--------------------------------------------------------------------------------

return LrWatermarkIndexDefinitions
