{
  "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
  "id": "data-sync",
  "name": "Data Synchronization",
  "description": "Synchronize data between SharePoint lists, Dataverse, or external APIs. Supports incremental sync with change tracking.",
  "category": "integration",
  "tags": ["sync", "data", "sharepoint", "integration"],
  "parameters": {
    "sourceSiteUrl": {
      "type": "string",
      "description": "Source SharePoint site URL",
      "required": true
    },
    "sourceListId": {
      "type": "string",
      "description": "Source list ID or name",
      "required": true
    },
    "targetSiteUrl": {
      "type": "string",
      "description": "Target SharePoint site URL",
      "required": true
    },
    "targetListId": {
      "type": "string",
      "description": "Target list ID or name",
      "required": true
    },
    "fieldMapping": {
      "type": "object",
      "description": "Field mapping from source to target",
      "required": true
    },
    "syncInterval": {
      "type": "number",
      "description": "Sync interval in minutes",
      "required": false,
      "default": 60
    },
    "syncMode": {
      "type": "string",
      "description": "Sync mode",
      "required": false,
      "default": "incremental",
      "enum": ["full", "incremental"]
    }
  },
  "connectionReferences": {
    "shared_sharepointonline": {
      "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",
      "tier": "Standard",
      "description": "SharePoint Online for reading and writing list items"
    }
  },
  "definition": {
    "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
    "contentVersion": "1.0.0.0",
    "triggers": {
      "Recurrence": {
        "type": "Recurrence",
        "recurrence": {
          "frequency": "Hour",
          "interval": 1
        }
      }
    },
    "actions": {
      "Initialize_sync_stats": {
        "type": "InitializeVariable",
        "inputs": {
          "variables": [{
            "name": "syncStats",
            "type": "Object",
            "value": {
              "created": 0,
              "updated": 0,
              "skipped": 0,
              "errors": 0,
              "startTime": "@{utcNow()}"
            }
          }]
        },
        "runAfter": {}
      },
      "Initialize_last_sync": {
        "type": "InitializeVariable",
        "inputs": {
          "variables": [{
            "name": "lastSyncTime",
            "type": "String",
            "value": "@{addDays(utcNow(), -1)}"
          }]
        },
        "runAfter": {
          "Initialize_sync_stats": ["Succeeded"]
        }
      },
      "Get_source_items": {
        "type": "OpenApiConnection",
        "inputs": {
          "host": {
            "apiId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",
            "connectionName": "shared_sharepointonline",
            "operationId": "GetItems"
          },
          "parameters": {
            "dataset": "@parameters('sourceSiteUrl')",
            "table": "@parameters('sourceListId')",
            "$filter": "Modified ge '@{variables('lastSyncTime')}'",
            "$orderby": "Modified asc"
          }
        },
        "runAfter": {
          "Initialize_last_sync": ["Succeeded"]
        },
        "description": "Get items modified since last sync"
      },
      "Process_each_item": {
        "type": "Foreach",
        "foreach": "@body('Get_source_items')?['value']",
        "actions": {
          "Check_if_exists": {
            "type": "OpenApiConnection",
            "inputs": {
              "host": {
                "apiId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",
                "connectionName": "shared_sharepointonline",
                "operationId": "GetItems"
              },
              "parameters": {
                "dataset": "@parameters('targetSiteUrl')",
                "table": "@parameters('targetListId')",
                "$filter": "SourceId eq '@{items('Process_each_item')?['ID']}'"
              }
            },
            "runAfter": {}
          },
          "Check_item_exists": {
            "type": "If",
            "expression": {
              "greater": [
                "@length(body('Check_if_exists')?['value'])",
                0
              ]
            },
            "actions": {
              "Update_existing_item": {
                "type": "OpenApiConnection",
                "inputs": {
                  "host": {
                    "apiId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",
                    "connectionName": "shared_sharepointonline",
                    "operationId": "PatchItem"
                  },
                  "parameters": {
                    "dataset": "@parameters('targetSiteUrl')",
                    "table": "@parameters('targetListId')",
                    "id": "@{first(body('Check_if_exists')?['value'])?['ID']}"
                  },
                  "body": {
                    "Title": "@{items('Process_each_item')?['Title']}",
                    "SourceId": "@{items('Process_each_item')?['ID']}",
                    "SyncedAt": "@{utcNow()}"
                  }
                },
                "runAfter": {}
              }
            },
            "else": {
              "actions": {
                "Create_new_item": {
                  "type": "OpenApiConnection",
                  "inputs": {
                    "host": {
                      "apiId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",
                      "connectionName": "shared_sharepointonline",
                      "operationId": "PostItem"
                    },
                    "parameters": {
                      "dataset": "@parameters('targetSiteUrl')",
                      "table": "@parameters('targetListId')"
                    },
                    "body": {
                      "Title": "@{items('Process_each_item')?['Title']}",
                      "SourceId": "@{items('Process_each_item')?['ID']}",
                      "SyncedAt": "@{utcNow()}"
                    }
                  },
                  "runAfter": {}
                }
              }
            },
            "runAfter": {
              "Check_if_exists": ["Succeeded"]
            }
          }
        },
        "runAfter": {
          "Get_source_items": ["Succeeded"]
        },
        "concurrency": {
          "repetitions": 5
        },
        "description": "Process each source item - create or update in target"
      },
      "Compose_summary": {
        "type": "Compose",
        "inputs": {
          "syncCompleted": "@{utcNow()}",
          "itemsProcessed": "@{length(body('Get_source_items')?['value'])}",
          "stats": "@variables('syncStats')"
        },
        "runAfter": {
          "Process_each_item": ["Succeeded"]
        }
      }
    }
  }
}
