name: Build and Publish Docker Image

on:
  push:
    tags:
      - '*'
    branches:
      - main
      - master
  workflow_dispatch:
    inputs:
      version:
        description: 'Version tag (e.g., V0.0.1-BETA)'
        required: true
        default: 'V0.0.1-BETA'

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Determine version tag
        id: version
        run: |
          if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
            echo "tag=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT
            echo "create_release=true" >> $GITHUB_OUTPUT
          elif [[ "${{ github.ref }}" == refs/tags/* ]]; then
            echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
            echo "create_release=true" >> $GITHUB_OUTPUT
          else
            echo "tag=latest" >> $GITHUB_OUTPUT
            echo "create_release=false" >> $GITHUB_OUTPUT
          fi

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=raw,value=${{ steps.version.outputs.tag }}
            type=raw,value=latest,enable=${{ steps.version.outputs.tag == 'latest' }}

      - 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: Create Release
        if: steps.version.outputs.create_release == 'true'
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.version.outputs.tag }}
          name: Release ${{ steps.version.outputs.tag }}
          body: |
            ## Release ${{ steps.version.outputs.tag }}
            
            Docker image is available at:
            - `${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.tag }}`
            
            ### Running the Docker image
            
            ```bash
            docker run -d -p 80:80 ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.tag }}
            ```
            
            The application will be available at http://localhost:80
          prerelease: true
          draft: false
