name: Deploy frontend to domestic test

on:
  workflow_dispatch:

jobs:
  deploy:
    name: Build and deploy isolated domestic test
    runs-on: gitea-label
    container:
      image: cozsweet-act-runner-node24-docker:latest
    env:
      NEXT_TELEMETRY_DISABLED: "1"
      SENTRY_UPLOAD_SOURCEMAPS: "0"

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Validate domestic SSH configuration
        env:
          SSH_HOST: ${{ secrets.DOMESTIC_TEST_SSH_HOST }}
          SSH_PORT: ${{ secrets.DOMESTIC_TEST_SSH_PORT }}
          SSH_PRIVATE_KEY_B64: ${{ secrets.DOMESTIC_TEST_SSH_PRIVATE_KEY_B64 }}
          SSH_KNOWN_HOSTS: ${{ secrets.DOMESTIC_TEST_SSH_KNOWN_HOSTS }}
        run: |
          set -eu
          if [ -z "$SSH_HOST" ] || [ -z "$SSH_PRIVATE_KEY_B64" ] || [ -z "$SSH_KNOWN_HOSTS" ]; then
            echo "Missing domestic test SSH secrets" >&2
            exit 1
          fi
          mkdir -p "$HOME/.ssh"
          chmod 700 "$HOME/.ssh"
          printf '%s' "$SSH_PRIVATE_KEY_B64" | base64 -d > "$HOME/.ssh/domestic_test_deploy_key"
          printf '%s\n' "$SSH_KNOWN_HOSTS" > "$HOME/.ssh/known_hosts"
          chmod 600 "$HOME/.ssh/domestic_test_deploy_key" "$HOME/.ssh/known_hosts"

      - name: Prepare domestic test environment
        env:
          TEST_ENV_FILE_CONTENT: ${{ secrets.TEST_ENV_FILE }}
        run: |
          set -eu
          if [ -z "$TEST_ENV_FILE_CONTENT" ]; then
            echo "Missing existing secret: TEST_ENV_FILE" >&2
            exit 1
          fi
          umask 077
          printf '%s\n' "$TEST_ENV_FILE_CONTENT" > .env.domestic-test

          replace_env() {
            key="$1"
            value="$2"
            awk -v key="$key" -v value="$value" '
              BEGIN { replaced = 0 }
              $0 ~ "^" key "=" { print key "=" value; replaced = 1; next }
              { print }
              END { if (!replaced) print key "=" value }
            ' .env.domestic-test > .env.domestic-test.next
            mv .env.domestic-test.next .env.domestic-test
          }

          replace_env NEXT_PUBLIC_APP_ENV test
          replace_env NEXT_PUBLIC_API_BASE_URL https://testapi.banlv-ai.com
          replace_env NEXT_PUBLIC_WS_BASE_URL wss://testapi.banlv-ai.com/ws
          replace_env NEXTAUTH_URL http://127.0.0.1:9135
          replace_env NEXTAUTH_URL_INTERNAL http://127.0.0.1:3000

          grep -Eq '^AUTH_SECRET=.+$' .env.domestic-test
          grep -Eq '^NEXT_PUBLIC_API_BASE_URL=https://testapi\.banlv-ai\.com/?$' .env.domestic-test
          grep -Eq '^NEXT_PUBLIC_WS_BASE_URL=wss://testapi\.banlv-ai\.com/ws/?$' .env.domestic-test

      - name: Prepare image metadata
        run: |
          set -eu
          SHORT_SHA="$(git rev-parse --short HEAD)"
          IMAGE="cozsweet-frontend-domestic-test:test-$SHORT_SHA"
          ARCHIVE="cozsweet-frontend-domestic-test-$SHORT_SHA.tar.gz"
          {
            echo "SHORT_SHA=$SHORT_SHA"
            echo "IMAGE=$IMAGE"
            echo "ARCHIVE=$ARCHIVE"
          } >> "$GITHUB_ENV"

      - name: Run frontend quality checks
        run: |
          set -eu
          pnpm install --frozen-lockfile
          pnpm lint
          pnpm typecheck
          pnpm test:contracts

      - name: Build and archive runtime image
        run: |
          set -eu
          DOCKER_BUILDKIT=1 docker build \
            --secret id=next_env,src=.env.domestic-test \
            --build-arg NEXT_ENV_FILE=.env.domestic-test \
            -t "$IMAGE" \
            .
          docker save "$IMAGE" | gzip -1 > "$ARCHIVE"
          test -s "$ARCHIVE"

      - name: Deploy isolated domestic test container
        env:
          SSH_HOST: ${{ secrets.DOMESTIC_TEST_SSH_HOST }}
          SSH_PORT: ${{ secrets.DOMESTIC_TEST_SSH_PORT }}
        run: |
          set -eu
          DEPLOY_PORT="${SSH_PORT:-22}"
          KEY_FILE="$HOME/.ssh/domestic_test_deploy_key"
          SSH_TARGET="lzf@$SSH_HOST"
          RUN_TOKEN="${GITHUB_RUN_ID:-manual}-${GITHUB_RUN_ATTEMPT:-1}"
          DEPLOY_ROOT="/home/lzf/apps/cozsweet-web-test"
          REMOTE_TMP="$DEPLOY_ROOT/tmp/actions-$RUN_TOKEN"
          REMOTE_ARCHIVE="$REMOTE_TMP/$ARCHIVE"
          REMOTE_ENV_FILE="$DEPLOY_ROOT/shared/test.env"
          SSH_OPTS="-i $KEY_FILE -p $DEPLOY_PORT -o BatchMode=yes -o IdentitiesOnly=yes"
          SCP_OPTS="-i $KEY_FILE -P $DEPLOY_PORT -o BatchMode=yes -o IdentitiesOnly=yes"

          cleanup_remote() {
            ssh $SSH_OPTS "$SSH_TARGET" \
              "rm -f '$REMOTE_ARCHIVE' && rmdir '$REMOTE_TMP' 2>/dev/null || true"
          }
          trap cleanup_remote EXIT

          ssh $SSH_OPTS "$SSH_TARGET" \
            "mkdir -p '$DEPLOY_ROOT/current' '$DEPLOY_ROOT/releases/docker' '$DEPLOY_ROOT/shared' '$REMOTE_TMP' && chmod 700 '$DEPLOY_ROOT/shared'"
          scp $SCP_OPTS scripts/server/deploy-domestic-test-archive.sh \
            "$SSH_TARGET:$DEPLOY_ROOT/current/deploy-domestic-test-archive.sh"
          scp $SCP_OPTS .env.domestic-test "$SSH_TARGET:$REMOTE_ENV_FILE"
          scp $SCP_OPTS "$ARCHIVE" "$SSH_TARGET:$REMOTE_ARCHIVE"
          ssh $SSH_OPTS "$SSH_TARGET" \
            "chmod 600 '$REMOTE_ENV_FILE' && chmod 700 '$DEPLOY_ROOT/current/deploy-domestic-test-archive.sh' && '$DEPLOY_ROOT/current/deploy-domestic-test-archive.sh' '$REMOTE_ARCHIVE' '$IMAGE' '$REMOTE_ENV_FILE' 9135"

      - name: Cleanup runner artifacts
        if: always()
        run: |
          rm -f .env.domestic-test .env.domestic-test.next "${ARCHIVE:-}" "$HOME/.ssh/domestic_test_deploy_key"
