#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e

write_root_state_files() {
  rm -rf node_modules packages
  mkdir -p node_modules/root_only
  cat > node_modules/root_only/index.js <<'EOF'
// @flow

export default 123;
EOF
}

write_nested_state_files() {
  rm -rf node_modules packages
  mkdir -p packages/app/node_modules/foo
  cat > packages/app/node_modules/foo/index.js <<'EOF'
// @flow

export default 123;
EOF
  cat > packages/app/consumer.js <<'EOF'
// @flow

import foo from 'foo';
foo as number;
EOF
}

printf "Creating saved state with root node_modules\n"
write_root_state_files
"$FLOW" start --saved-state-fetcher none --wait
"$FLOW" save-state --out .flow.saved_state_root >> /dev/null
"$FLOW" stop
echo

printf "Creating saved state with nested node_modules\n"
write_nested_state_files
"$FLOW" start --saved-state-fetcher none --wait
"$FLOW" save-state --out .flow.saved_state_nested >> /dev/null
"$FLOW" stop
echo

printf "Loading saved state with root node_modules\n"
write_root_state_files
cp .flow.saved_state_root .flow.saved_state
: > .flow.saved_state_file_changes
"$FLOW" start \
  --file-watcher=none \
  --saved-state-fetcher=local \
  --saved-state-no-fallback \
  --lazy-mode=true \
  --wait
assert_ok "$FLOW" status --no-auto-start > /dev/null
echo

printf "Reinitializing with saved state with nested node_modules\n"
write_nested_state_files
cp .flow.saved_state_nested .flow.saved_state
: > .flow.saved_state_file_changes
assert_ok "$FLOW" force-recheck --missed-changes --changed-mergebase packages/app/consumer.js
assert_ok "$FLOW" status --no-auto-start > /dev/null
echo

printf "find-module resolves package from reinit saved state:\n"
assert_ok "$FLOW" find-module --strip-root foo packages/app/consumer.js
echo

printf "check-contents resolves package from reinit saved state:\n"
assert_ok "$FLOW" check-contents --strip-root packages/app/consumer.js <<'EOF'
// @flow

import foo from 'foo';
foo as number;
EOF
echo

assert_ok "$FLOW" stop
