version: 0.2

env:
  variables:
    AWS_REGION: eu-north-1
    ECR_REPO: eclipse-solitaire-backend
    CONTAINER_NAME: backend

phases:
  pre_build:
    commands:
      - set -euo pipefail
      - echo "Logging in to Amazon ECR..."
      - aws --version
      - ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)"
      - ECR_HOST="${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
      - ECR_URI="${ECR_HOST}/${ECR_REPO}"
      - echo "ACCOUNT_ID=${ACCOUNT_ID}"
      - echo "ECR_URI=${ECR_URI}"
      - aws ecr get-login-password --region "${AWS_REGION}" | docker login --username AWS --password-stdin "${ECR_HOST}"
      - aws ecr describe-repositories --repository-names "${ECR_REPO}" --region "${AWS_REGION}" || aws ecr create-repository --repository-name "${ECR_REPO}" --region "${AWS_REGION}"
      - RAW_TAG="${CODEBUILD_RESOLVED_SOURCE_VERSION:-latest}"
      - IMAGE_TAG="$(echo "${RAW_TAG}" | cut -c1-12)"
      - if [ -z "${IMAGE_TAG}" ]; then IMAGE_TAG=latest; fi
      - echo "IMAGE_TAG=${IMAGE_TAG}"

  build:
    commands:
      - echo "Building Docker image..."
      - docker build -t "${ECR_REPO}:${IMAGE_TAG}" .
      - docker tag "${ECR_REPO}:${IMAGE_TAG}" "${ECR_URI}:${IMAGE_TAG}"

  post_build:
    commands:
      - echo "Pushing image to ECR..."
      - docker push "${ECR_URI}:${IMAGE_TAG}"
      - echo "Writing imageDetail.json for CodeDeploy..."
      - mkdir -p scripts
      - "printf '{\"imageUri\":\"%s\"}\\n' \"${ECR_URI}:${IMAGE_TAG}\" > scripts/imageDetail.json"
      - echo "Artifact will include: appspec.yml and scripts/*"

artifacts:
  files:
    - appspec.yml
    - scripts/**/*
