name: Lambda smoke test

on:
  workflow_call:
    inputs:
      dockerfile_path:
        required: true
        type: string
      build_context:
        required: false
        default: "."
        type: string
      service_name:
        required: true
        type: string

jobs:
  smoke-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Download AWS Lambda RIE
        run: |
          mkdir -p ~/.aws-lambda-rie
          curl -fsSL -o ~/.aws-lambda-rie/aws-lambda-rie \
            https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie
          chmod +x ~/.aws-lambda-rie/aws-lambda-rie

      - name: Build Lambda image
        run: |
          docker build \
            --platform linux/amd64 \
            -f ${{ inputs.dockerfile_path }} \
            -t ${{ inputs.service_name }}-smoke-test:latest \
            ${{ inputs.build_context }}

      - name: Start Lambda container
        run: |
          IMG=${{ inputs.service_name }}-smoke-test:latest
          ENTRY=$(docker inspect --format='{{range .Config.Entrypoint}}{{.}} {{end}}' "$IMG")
          CMD_ARGS=$(docker inspect --format='{{range .Config.Cmd}}{{.}} {{end}}' "$IMG")

          if echo "$ENTRY" | grep -q "lambda-entrypoint.sh"; then
            # AWS base image — RIE is bundled
            docker run -d --name ${{ inputs.service_name }}-smoke-test \
              -p 9000:8080 \
              "$IMG"
          else
            # Custom base — mount RIE from runner and re-wire entrypoint
            docker run -d --name ${{ inputs.service_name }}-smoke-test \
              -v "$HOME/.aws-lambda-rie:/aws-lambda-rie" \
              -p 9000:8080 \
              --entrypoint /aws-lambda-rie/aws-lambda-rie \
              "$IMG" \
              $ENTRY $CMD_ARGS
          fi

      - name: Invoke Lambda and check for import errors
        run: |
          response=$(curl -s --retry-connrefused --retry 15 --retry-delay 1 \
            -X POST \
            http://localhost:9000/2015-03-31/functions/function/invocations \
            -H "Content-Type: application/json" \
            -d '{"Records":[{"body":"{}"}]}')

          echo "Response: $response"

          if [ -z "$response" ]; then
            echo "No response from Lambda RIE"
            exit 1
          fi

          if echo "$response" | grep -qE 'ImportModuleError|ModuleNotFoundError|ImportError'; then
            echo "Import error detected in handler"
            exit 1
          fi

      - name: Dump container logs
        if: always()
        run: docker logs ${{ inputs.service_name }}-smoke-test

      - name: Tear down container
        if: always()
        run: docker rm -f ${{ inputs.service_name }}-smoke-test
