name: Build and Deploy Docker Images

on:
  workflow_dispatch:
    inputs:
      ref:
        description: Git Ref
        required: true
        type: string

jobs:
  build:
    name: build
    runs-on: ubuntu-latest
    permissions:
      packages: write
      contents: read
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{inputs.ref}}
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Buildx
        uses: docker/setup-buildx-action@v3

      - name: Calculate Image Tags
        env:
          INPUT_REF: ${{inputs.ref}}
        run: |
          declare TAGS=""
          case "${INPUT_REF}" in
          v[0-9]*.[0-9]*.[0-9]*)
            TAGS="${INPUT_REF}"
            if [[ "$(git rev-parse origin/main)" = "$(git rev-parse "${INPUT_REF}")" ]]; then
              TAGS="${TAGS} latest"
            fi
            CHANNEL="stable"
            ;;
          [0-9]*.[0-9]*.[0-9]*-nightly)
            TAGS="${INPUT_REF} nightly"
            CHANNEL="nightly"
            ;;
          *)
            echo "Invalid Input Ref: ${INPUT_REF}"
            exit 1
          esac

          if [[ -z "${TAGS}" ]]; then
            echo "Empty Tags!"
            exit 1
          fi

          {
            echo 'DOCKER_IMAGE_TAGS<<EOF'
            for tag in ${TAGS}; do
            echo "viren070/aiostreams:${tag}"
            echo "ghcr.io/viren070/aiostreams:${tag}"
            done
            echo EOF
          } >> "${GITHUB_ENV}"

          echo "TAGS=${TAGS}" >> "${GITHUB_ENV}"

          echo "CHANNEL=${CHANNEL}" >> "${GITHUB_ENV}"

          cat "${GITHUB_ENV}"

      - name: Node
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Generate metadata
        run: |
          node scripts/generateMetadata.cjs --channel=${{env.CHANNEL}}

      - name: Build & Push
        uses: docker/build-push-action@v6
        with:
          cache-from: type=gha
          cache-to: type=gha,mode=max
          platforms: linux/amd64,linux/arm64
          push: true
          context: .
          file: ./Dockerfile
          tags: ${{env.DOCKER_IMAGE_TAGS}}

      - name: Send Discord Notification
        env:
          CHANNEL: ${{env.CHANNEL}}
          TAGS: ${{env.TAGS}}
        run: |
          # Determine role based on channel
          if [ "$CHANNEL" = "stable" ]; then
            ROLE_ID="<@&1384627130272452638>"
            COLOR=5763719  # Green
            TITLE="🎉 Stable Release"
          else
            ROLE_ID="<@&1384627462155272242>"
            COLOR=15844367  # Orange
            TITLE="🌙 Nightly Build"
          fi

          # Format tags for display (each tag on a new line with bullet points)
          FORMATTED_TAGS=""
          for tag in $TAGS; do
            if [ -z "$FORMATTED_TAGS" ]; then
              FORMATTED_TAGS="• \`$tag\`"
            else
              FORMATTED_TAGS="$FORMATTED_TAGS\n• \`$tag\`"
            fi
          done

          # Get current timestamp in ISO 8601 format UTC
          TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

          # Create JSON payload file
          cat << EOF > discord_payload.json
          {
            "content": "$ROLE_ID",
            "embeds": [
              {
                "title": "$TITLE - Docker Images Published",
                "description": "New Docker images have been built and pushed to registries.",
                "color": $COLOR,
                "fields": [
                  {
                    "name": "📦 Channel",
                    "value": "• \`$CHANNEL\`",
                    "inline": true
                  },
                  {
                    "name": "🏷️ Tags Published",
                    "value": "$FORMATTED_TAGS",
                    "inline": false
                  },
                  {
                    "name": "📍 View Images",
                    "value": "[Docker Hub](https://hub.docker.com/r/viren070/aiostreams) · [GHCR](https://github.com/Viren070/AIOStreams/pkgs/container/aiostreams)",
                    "inline": false
                  },
                  {
                    "name": "📝 View Release Notes",
                    "value": "[GitHub](https://github.com/Viren070/AIOStreams/releases/tag/${{ inputs.ref }})",
                    "inline": false
                  },
                  {
                    "name": "🔗 View Build",
                    "value": "[GitHub Actions](https://github.com/Viren070/aiostreams/actions/runs/${{ github.run_id }})",
                    "inline": false
                  }
                ],
                "footer": {
                  "text": "AIOStreams CI",
                  "icon_url": "https://github.com/Viren070.png"
                },
                "timestamp": "$TIMESTAMP"
              }
            ]
          }
          EOF

          echo "Sending to Discord:"
          cat discord_payload.json

          # Send payload to Discord and capture response and status code
          http_response=$(curl -s -w "\n%{http_code}" -H "Content-Type: application/json" \
            -X POST \
            -d @discord_payload.json \
            "${{ secrets.DISCORD_WEBHOOK_URL }}")

          http_body=$(echo "$http_response" | sed '$d')
          http_code=$(echo "$http_response" | tail -n1)

          echo "HTTP Status Code: $http_code"
          echo "Discord Response Body: $http_body"

          if [ "$http_code" != "204" ]; then
            echo "Error sending to Discord webhook."
            exit 1
          fi

          echo "Message sent successfully!"
