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 gg          = "http://art-decor.org/ns/decor/governancegroups" at "../api/api-decor-governancegroups.xqm";
declare namespace request           = "http://exist-db.org/xquery/request";

(:
Expected structure in request: request:get-data()//group[string-length(@id)>0]
This xquery saves either

A)
the governance group link to be established for the project in the project collection named
governance-group-links.xml as requested
If file governance-group-links.xml does not exist a new one is created

<governance-group-links projectId="...">
  <partOf governanceId="..."/>
</governance-group-links>

B)
or all (updated) governance group definitions, wrapped by some element, to add/update content of file art-data / hosted-governance-groups.xml.
Deletion currently not supported. If file hosted-governance-groups.xml does not exist a new one is created

<result>
  <group id="..." defaultLanguage="...">
  ...
  </group>
  <group id="..." defaultLanguage="...">
  ...
  </group>
</result>

:)

let $groups     := if (request:exists()) then request:get-data()//group else ()
let $groups     := $groups[string-length(@id)>0]
let $action     := $groups/@action
    
let $res        :=
    (: ------------ save link to governance group for a specific project ------------ :)
    if ($action=('link','unlink')) then (
        gg:saveGroupLinks($groups)
    )
    (: ------------ save governance all group definitions for this server ------------ :)
    else (
        gg:saveGroups($groups)
    )
    
return ()
