name: Docker Image

on:
  push:
    branches:
      - main
      - test
  workflow_dispatch:

jobs:
  publish:
    name: Build and Push Docker Image
    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: Verify Docker
        run: |
          node --version
          pnpm --version
          docker version
          docker info

      - name: Prepare image metadata
        env:
          REGISTRY_IMAGE: ${{ secrets.REGISTRY_IMAGE }}
        run: |
          set -eu

          BRANCH_NAME="${GITHUB_REF_NAME:-}"
          if [ -z "$BRANCH_NAME" ] && [ -n "${GITHUB_REF:-}" ]; then
            BRANCH_NAME="${GITHUB_REF#refs/heads/}"
          fi
          if [ -z "$BRANCH_NAME" ]; then
            BRANCH_NAME="$(git branch --show-current)"
          fi

          SHORT_SHA="$(git rev-parse --short HEAD)"
          case "$BRANCH_NAME" in
            main)
              DEPLOY_ENV="prod"
              NEXT_ENV_FILE=".env.production"
              ;;
            test)
              DEPLOY_ENV="test"
              NEXT_ENV_FILE=".env.local"
              ;;
            *)
              echo "Unsupported branch for image publishing: $BRANCH_NAME" >&2
              exit 1
              ;;
          esac

          if [ -z "$REGISTRY_IMAGE" ]; then
            echo "Missing secret: REGISTRY_IMAGE" >&2
            exit 1
          fi

          {
            echo "BRANCH_NAME=$BRANCH_NAME"
            echo "DEPLOY_ENV=$DEPLOY_ENV"
            echo "NEXT_ENV_FILE=$NEXT_ENV_FILE"
            echo "SHORT_SHA=$SHORT_SHA"
            echo "IMAGE=$REGISTRY_IMAGE"
            echo "IMAGE_VERSION_TAG=$REGISTRY_IMAGE:$DEPLOY_ENV-$SHORT_SHA"
            echo "IMAGE_LATEST_TAG=$REGISTRY_IMAGE:$DEPLOY_ENV-latest"
          } >> "$GITHUB_ENV"

      - name: Prepare build env file
        env:
          TEST_ENV_FILE_CONTENT: ${{ secrets.TEST_ENV_FILE }}
          PRODUCTION_ENV_FILE_CONTENT: ${{ secrets.PRODUCTION_ENV_FILE }}
        run: |
          set -eu

          case "$DEPLOY_ENV" in
            prod)
              if [ -z "$PRODUCTION_ENV_FILE_CONTENT" ]; then
                echo "Missing secret: PRODUCTION_ENV_FILE" >&2
                exit 1
              fi
              printf '%s\n' "$PRODUCTION_ENV_FILE_CONTENT" > "$NEXT_ENV_FILE"
              ;;
            test)
              if [ -z "$TEST_ENV_FILE_CONTENT" ]; then
                echo "Missing secret: TEST_ENV_FILE" >&2
                exit 1
              fi
              printf '%s\n' "$TEST_ENV_FILE_CONTENT" > "$NEXT_ENV_FILE"
              ;;
          esac

      - name: Login Docker registry
        env:
          REGISTRY_HOST: ${{ secrets.REGISTRY_HOST }}
          REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
          REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
        run: |
          set -eu

          if [ -z "$REGISTRY_HOST" ] || [ -z "$REGISTRY_USERNAME" ] || [ -z "$REGISTRY_PASSWORD" ]; then
            echo "Missing registry login secrets" >&2
            exit 1
          fi

          printf '%s' "$REGISTRY_PASSWORD" \
            | docker login "$REGISTRY_HOST" -u "$REGISTRY_USERNAME" --password-stdin

      - name: Build Docker image
        run: |
          set -eu

          DOCKER_BUILDKIT=1 docker build \
            --secret id=next_env,src="$NEXT_ENV_FILE" \
            --build-arg NEXT_ENV_FILE="$NEXT_ENV_FILE" \
            -t "$IMAGE_VERSION_TAG" \
            -t "$IMAGE_LATEST_TAG" \
            .

      - name: Push Docker image
        run: |
          set -eu

          docker push "$IMAGE_VERSION_TAG"
          docker push "$IMAGE_LATEST_TAG"

      - name: Prune Gitea registry images
        env:
          REGISTRY_API_BASE_URL: ${{ secrets.REGISTRY_API_BASE_URL }}
          REGISTRY_PACKAGE_TOKEN: ${{ secrets.REGISTRY_PACKAGE_TOKEN }}
        run: |
          set -eu

          if [ -z "$REGISTRY_PACKAGE_TOKEN" ]; then
            echo "Missing secret: REGISTRY_PACKAGE_TOKEN" >&2
            exit 1
          fi

          REGISTRY_API_BASE_URL="${REGISTRY_API_BASE_URL:-https://gitea.banlv-ai.com/api/v1}" \
            REGISTRY_PACKAGE_KEEP_COUNT=3 \
            bash scripts/ci/prune-gitea-container-images.sh

      - name: Deploy image over SSH
        env:
          SSH_HOST: ${{ secrets.SSH_HOST }}
          SSH_USER: ${{ secrets.SSH_USER }}
          SSH_PORT: ${{ secrets.SSH_PORT }}
          SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
          SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
          TEST_DEPLOY_DIR: ${{ secrets.TEST_DEPLOY_DIR }}
          PROD_DEPLOY_DIR: ${{ secrets.PROD_DEPLOY_DIR }}
          REGISTRY_HOST: ${{ secrets.REGISTRY_HOST }}
          REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
          REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
        run: |
          set -eu

          case "$DEPLOY_ENV" in
            test)
              DEPLOY_DIR="${TEST_DEPLOY_DIR:-/opt/cozsweet-web-test}"
              HOST_PORT="9135"
              CONTAINER_NAME="cozsweet-web-test"
              PROJECT_NAME="cozsweet-web-test"
              ;;
            prod)
              DEPLOY_DIR="${PROD_DEPLOY_DIR:-/opt/cozsweet-web-prod}"
              HOST_PORT="9185"
              CONTAINER_NAME="cozsweet-web-prod"
              PROJECT_NAME="cozsweet-web-prod"
              ;;
            *)
              echo "Unsupported deploy env: $DEPLOY_ENV" >&2
              exit 1
              ;;
          esac

          DEPLOY_HOST="$SSH_HOST"
          DEPLOY_USER="$SSH_USER"
          DEPLOY_PORT="${SSH_PORT:-22}"
          DEPLOY_KEY="$SSH_PRIVATE_KEY"
          DEPLOY_KNOWN_HOSTS="$SSH_KNOWN_HOSTS"

          if [ -z "$DEPLOY_HOST" ] || [ -z "$DEPLOY_USER" ] || [ -z "$DEPLOY_KEY" ]; then
            echo "Missing SSH deployment secrets for $DEPLOY_ENV" >&2
            exit 1
          fi

          mkdir -p ~/.ssh
          chmod 700 ~/.ssh
          KEY_FILE="$HOME/.ssh/cozsweet_deploy_key"
          printf '%s\n' "$DEPLOY_KEY" > "$KEY_FILE"
          chmod 600 "$KEY_FILE"

          if [ -n "$DEPLOY_KNOWN_HOSTS" ]; then
            printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
          else
            ssh-keyscan -p "$DEPLOY_PORT" "$DEPLOY_HOST" >> ~/.ssh/known_hosts
          fi

          SSH_TARGET="$DEPLOY_USER@$DEPLOY_HOST"
          SSH_OPTS="-i $KEY_FILE -p $DEPLOY_PORT -o IdentitiesOnly=yes"
          SCP_OPTS="-i $KEY_FILE -P $DEPLOY_PORT -o IdentitiesOnly=yes"

          ssh $SSH_OPTS "$SSH_TARGET" "mkdir -p '$DEPLOY_DIR'"
          scp $SCP_OPTS docker-compose.yml "$SSH_TARGET:$DEPLOY_DIR/docker-compose.yml"
          scp $SCP_OPTS scripts/server/deploy-docker-image.sh "$SSH_TARGET:$DEPLOY_DIR/deploy-docker-image.sh"
          scp $SCP_OPTS "$NEXT_ENV_FILE" "$SSH_TARGET:$DEPLOY_DIR/$NEXT_ENV_FILE"

          printf '%s' "$REGISTRY_PASSWORD" \
            | ssh $SSH_OPTS "$SSH_TARGET" \
                "docker login '$REGISTRY_HOST' -u '$REGISTRY_USERNAME' --password-stdin"

          SERVER_RETAIN_COUNT="0"
          if [ "$DEPLOY_ENV" = "prod" ]; then
            SERVER_RETAIN_COUNT="1"
          fi

          ssh $SSH_OPTS "$SSH_TARGET" \
            "cd '$DEPLOY_DIR' && chmod +x ./deploy-docker-image.sh && ./deploy-docker-image.sh '$IMAGE_VERSION_TAG' '$NEXT_ENV_FILE' '$HOST_PORT' '$CONTAINER_NAME' '$PROJECT_NAME' '$SERVER_RETAIN_COUNT'"

      - name: Purge Cloudflare cache
        env:
          CF_ZONE_ID: ${{ secrets.CF_ZONE_ID }}
          CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }}
        run: |
          set -eu

          if [ -z "$CF_ZONE_ID" ] || [ -z "$CF_API_TOKEN" ]; then
            echo "Cloudflare secrets are not configured, skip purge."
            exit 0
          fi

          curl -fsS -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/purge_cache" \
            -H "Authorization: Bearer $CF_API_TOKEN" \
            -H "Content-Type: application/json" \
            -d '{"purge_everything":true}'

      - name: Cleanup build env file
        if: always()
        run: |
          rm -f .env.local .env.production

      - name: Notify action result
        if: always()
        env:
          ACTION_JOB_STATUS: ${{ job.status }}
          ACTION_NOTIFY_WEBHOOK_URL: ${{ secrets.ACTION_NOTIFY_WEBHOOK_URL }}
        run: |
          bash scripts/ci/notify-actions.sh
