name: "Build and Push to ECR"
description: "Authenticate via OIDC, build Docker image, and push to ECR"

inputs:
  image_name:
    description: "ECR repository name"
    required: true
  dockerfile:
    description: "Path to Dockerfile"
    required: true
  context:
    description: "Docker build context"
    required: true
    default: "."
  aws_role:
    description: "IAM role ARN to assume via OIDC"
    required: true
  aws_region:
    description: "AWS region"
    required: true
    default: "us-east-1"
  tag_prefix:
    description: "Prefix for image tags (e.g. executor, dashboard)"
    required: true
  platform:
    description: "Docker platform"
    required: false
    default: "linux/amd64"

outputs:
  image_uri:
    description: "Full image URI with tag"
    value: ${{ steps.meta.outputs.tags }}
  short_sha:
    description: "Short git SHA used in tags"
    value: ${{ steps.vars.outputs.short_sha }}

runs:
  using: "composite"
  steps:
    - name: Set variables
      id: vars
      shell: bash
      run: echo "short_sha=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"

    - name: Configure AWS credentials
      uses: aws-actions/configure-aws-credentials@v4
      with:
        role-to-assume: ${{ inputs.aws_role }}
        aws-region: ${{ inputs.aws_region }}

    - name: Login to Amazon ECR
      id: login-ecr
      uses: aws-actions/amazon-ecr-login@v2

    - name: Extract metadata (tags, labels)
      id: meta
      uses: docker/metadata-action@v5
      with:
        images: ${{ steps.login-ecr.outputs.registry }}/${{ inputs.image_name }}
        tags: |
          type=sha,format=long,prefix=${{ inputs.tag_prefix }}-
          type=sha,prefix=${{ inputs.tag_prefix }}-
          type=raw,value=${{ inputs.tag_prefix }}-latest,enable={{is_default_branch}}

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

    - name: Build and push
      uses: docker/build-push-action@v5
      with:
        context: ${{ inputs.context }}
        file: ${{ inputs.dockerfile }}
        push: true
        tags: ${{ steps.meta.outputs.tags }}
        labels: ${{ steps.meta.outputs.labels }}
        platforms: ${{ inputs.platform }}
        cache-from: type=gha
        cache-to: type=gha,mode=max
        build-args: |
          GIT_COMMIT=${{ github.sha }}
