#!/usr/bin/env bash

setup_file(){
  load "$PWD/tests/integration/helpers/common"
  _common_setup
  _add_server
  _new_app
}

teardown_file(){
  _rm_app
  _rm_server
}

setup(){
  load "$PWD/tests/integration/helpers/common"
  _common_setup
}

teardown(){
  if [[ ! -f "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env" ]]; then
    _new_app
  fi

  _undeploy_app
}

@test "validate app argument" {
  run $ABRA app deploy
  assert_failure

  run $ABRA app deploy DOESNTEXIST
  assert_failure
}

@test "do not show ALERTA warning if --force / --no-input" {
  run $ABRA app rm "$TEST_APP_DOMAIN" --force
  refute_output --partial 'ALERTA'

  run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
  refute_output --partial 'ALERTA'
}

# bats test_tags=slow
@test "error if still deployed" {
  _deploy_app

  run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
  assert_failure
  assert_output --partial 'is still deployed'
}

@test "detect no secrets to remove" {
  run $ABRA app secret ls "$TEST_APP_DOMAIN"
  assert_success
  assert_output --partial 'test_pass_one'

  run $ABRA app secret rm "$TEST_APP_DOMAIN" --all --no-input
  assert_success

  run $ABRA app secret ls "$TEST_APP_DOMAIN"
  assert_success
  assert_output --partial 'test_pass_one'
  assert_output --partial 'false'

  run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
  assert_success
  assert_output --partial 'no secrets to remove'
}

@test "remove secrets" {
  run $ABRA app secret generate "$TEST_APP_DOMAIN" --all
  assert_failure
  assert_output --partial 'already exists'

  run $ABRA app secret ls "$TEST_APP_DOMAIN"
  assert_success
  assert_output --partial 'test_pass_one'

  run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
  assert_success
  refute_output --partial 'no secrets to remove'

  sanitisedDomainName="${TEST_APP_DOMAIN//./_}"
  assert_output --partial "$sanitisedDomainName_test_pass_one_v1 removed"
}

# bats test_tags=slow
@test "detect no volumes to remove" {
  _deploy_app

  run $ABRA app volume ls "$TEST_APP_DOMAIN"
  assert_success
  assert_output --partial 'test-volume'

  _undeploy_app

  run $ABRA app volume rm "$TEST_APP_DOMAIN" --no-input
  assert_success

  run $ABRA app volume ls "$TEST_APP_DOMAIN"
  assert_success
  refute_output --partial 'test-volume'
  assert_output --partial 'no volumes created'

  run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
  assert_success
  assert_output --partial 'no volumes to remove'
}

# bats test_tags=slow
@test "remove volumes" {
  _deploy_app

  run $ABRA app volume ls "$TEST_APP_DOMAIN"
  assert_success
  assert_output --partial 'test-volume'

  _undeploy_app

  run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
  assert_success
  assert_output --partial 'test-volume'
  assert_output --partial 'removed'
}

@test "remove .env file" {
  assert_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"

  run $ABRA app rm "$TEST_APP_DOMAIN" --no-input
  assert_success

  assert_not_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
}
