#!/bin/bash

if [ "$#" -lt 2 ]; then
  echo "Usage: $0 DOCKER_CONTAINER_NAME DB_NAME"
  exit 1
fi

DOCKER_CONTAINER_NAME="$1"
DB_NAME="$2"

UPDATE_MODIFIED_FILTER='
{
  $expr: {
    $ne: [
      {
        $type: "$modified_at"
      },
      "long"
    ]
  }
}
'

UPDATE_MODIFIED_COMMAND='[
  {
    "$set": {
      "modified_at": {
        $toLong: {
          $multiply: [
            {
              $toLong: "$modified_at"
            },
            1000000
          ]
        }
      }
    }
  }
]'

echo "Updating collection history - modified_at timestamp"

docker exec -i "$DOCKER_CONTAINER_NAME" mongosh "$DB_NAME" --eval "
  db.collections_history.updateMany($UPDATE_MODIFIED_FILTER, $UPDATE_MODIFIED_COMMAND)
"

if [ $? -eq 0 ]; then
  echo "Successfully updated collection history"
else
  >&2 echo "Failed to update collection history"
fi

UPDATE_DIFFERENCES_FILTER='
{
  "differences.field": {
    "$in": [
      "__modified_at",
      "__created_at"
    ]
  },
  "differences.content": {
    "$type": "date"
  }
}
'

UPDATE_DIFFERENCES_COMMAND='[
  {
    "$set": {
      "differences": {
        "$map": {
          "input": "$differences",
          "as": "elem",
          "in": {
            "$cond": {
              "if": {
                "$and": [
                  {
                    "$in": [
                      "$$elem.field",
                      [
                        "__modified_at",
                        "__created_at"
                      ]
                    ]
                  },
                  {
                    "$eq": [
                      {
                        "$type": "$$elem.content"
                      },
                      "date"
                    ]
                  }
                ]
              },
              "then": {
                "$mergeObjects": [
                  "$$elem",
                  {
                    "content": {
                      "$toLong": {
                        "$multiply": [
                          {
                            "$toLong": {
                              "$toDate": "$$elem.content"
                            }
                          },
                          1000000
                        ]
                      }
                    }
                  }
                ]
              },
              "else": "$$elem"
            }
          }
        }
      }
    }
  }
]'

echo "Updating collection history - differences timestamp"

docker exec -i "$DOCKER_CONTAINER_NAME" mongosh "$DB_NAME" --eval "
  db.collections_history.updateMany($UPDATE_DIFFERENCES_FILTER, $UPDATE_DIFFERENCES_COMMAND)
"

if [ $? -eq 0 ]; then
  echo "Successfully updated collection history"
else
  >&2 echo "Failed to update collection history"
fi
