name: Build and Push Docker Image

on:
  push:
    branches:
      - main
  workflow_dispatch:

env:
  IMAGE_NAME: karaokepedia

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      # Uncomment if using GitHub Container Registry
      # - name: Log in to GitHub Container Registry
      #   uses: docker/login-action@v3
      #   with:
      #     registry: ghcr.io
      #     username: ${{ github.actor }}
      #     password: ${{ secrets.GITHUB_TOKEN }}

      # Uncomment if using Gitea Container Registry
      # - name: Log in to Gitea Container Registry
      #   uses: docker/login-action@v3
      #   with:
      #     registry: gitea.yourdomain.com
      #     username: ${{ secrets.GITEA_USERNAME }}
      #     password: ${{ secrets.GITEA_PASSWORD }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ secrets.DOCKER_USERNAME }}/${{ env.IMAGE_NAME }}
          # Use this for GHCR:
          # images: ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}
          # Use this for Gitea:
          # images: gitea.yourdomain.com/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}
          tags: |
            type=raw,value=latest
            type=sha,prefix={{branch}}-

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Image digest
        run: echo ${{ steps.meta.outputs.digest }}
