xquery version "1.0";
(:
    ART-DECOR® STANDARD COPYRIGHT AND LICENSE NOTE
    Copyright © ART-DECOR Expert Group and ART-DECOR Open Tools GmbH
    see https://docs.art-decor.org/copyright and https://docs.art-decor.org/licenses

    This file is part of the ART-DECOR® tools suite.
:)
import module namespace hist     = "http://art-decor.org/ns/decor/history" at "../api/api-decor-history.xqm";

declare %private function local:reindexHistory() {
(: 2.2-LTS or 4.0.0 and up :)
let $system-version     := tokenize(system:get-version(), '\.')[1]
(: new range appears stable from version 4 and up:)
let $use-new-range      := if ($system-version castable as xs:integer) then xs:integer($system-version) ge 4 else false()

let $decorHistoryConf   := if ($use-new-range) then local:getDecorHistoryIndexV4() else local:getDecorHistoryIndexV2()
let $update             := xmldb:create-collection(concat('/db/system/config', repo:get-root()), 'decor/history')
let $update             := xmldb:store($update, 'collection.xconf', $decorHistoryConf)
let $update             := xmldb:reindex(xmldb:create-collection(repo:get-root(), 'decor/history'))

return ()
};
(: keep in sync with art/pre-install.xql :)
declare %private function local:getDecorHistoryIndexV2() as element() {
<collection xmlns="http://exist-db.org/collection-config/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <!-- decor/history index definition for eXist 2.2 -->
    <index>
        <fulltext default="none" attributes="false"/>
        <create qname="@artefactType" type="xs:string"/>
        <create qname="@projectPrefix" type="xs:string"/>
        <create qname="@artefactId" type="xs:string"/>
        <create qname="@artefactEffectiveDate" type="xs:string"/>
        <create qname="@date" type="xs:string"/>
    </index>
</collection>
};
declare %private function local:getDecorHistoryIndexV4() as element() {
<collection xmlns="http://exist-db.org/collection-config/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <!-- decor/history index definition for eXist 4.3.1 and up -->
    <index>
        <fulltext default="none" attributes="false"/>
        <range>
            <create qname="@artefactType" type="xs:string"/>
            <create qname="@projectPrefix" type="xs:string"/>
            <create qname="@artefactId" type="xs:string"/>
            <create qname="@artefactEffectiveDate" type="xs:string"/>
            <create qname="@date" type="xs:string"/>
        </range>
    </index>
</collection>
};

let $statusonly         := if (request:exists()) then request:get-parameter('statusonly', 'true')='true' else (true())

let $update             := hist:ConvertHistory($statusonly)
let $updateHistoryIndex := if ($statusonly) then () else local:reindexHistory()

return
    <result dateTime="{current-dateTime()}" statusOnly="{$statusonly}">{$update}</result>