name: Build and Push Docker Images

on:
  push:
    branches: [main]
    tags: ['v*']
    paths:
      - 'backend/**'
      - 'frontend/**'
      - 'docker-compose.yml'
      - 'docker-compose.dev.yml'
      - '.github/workflows/docker-build.yml'
  workflow_dispatch:
    inputs:
      tag:
        description: 'Image/release tag (e.g. v1.19.1 or latest)'
        required: false
        default: ''
      create_release:
        description: 'Create GitHub release entry (requires tag starting with v)'
        required: false
        default: false
        type: boolean

concurrency:
  group: docker-build-${{ github.ref }}
  cancel-in-progress: true

# Default minimal permissions
permissions:
  contents: read

env:
  REGISTRY: ghcr.io

jobs:
  # =============================================================================
  # Build and Push Docker Images
  # Triggered on pushes to main (tagged as "main") and version tags (v*).
  # Tests are NOT run here — branch protection on main requires all PR checks
  # (backend-test + frontend-build from test.yml) to pass before merge.
  # Tags are created from main, so code is already tested.
  #
  # main push  → "main" tag only (for testing before release)
  # Tag builds → semver tags (e.g., 1.9.0, 1.9) plus "latest"
  # =============================================================================
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    strategy:
      matrix:
        include:
          - context: ./backend
            image: backend
          - context: ./frontend
            image: frontend

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

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

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

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v6
        with:
          images: ${{ env.REGISTRY }}/${{ github.repository_owner }}/medassist-ng-${{ matrix.image }}
          tags: |
            type=ref,event=branch
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
            type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }}

      - name: Build and push
        uses: docker/build-push-action@v7
        with:
          context: ${{ matrix.context }}
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          platforms: linux/amd64,linux/arm64
          provenance: false
          sbom: false

  # =============================================================================
  # Create GitHub Release (on tag push or manual dispatch with create_release)
  # =============================================================================
  create-release:
    runs-on: ubuntu-latest
    needs: build-and-push
    if: startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && github.event.inputs.create_release == 'true')
    permissions:
      contents: write
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0  # Fetch all history for changelog generation

      - name: Resolve current tag
        id: current_tag
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            CURRENT_TAG="${{ github.event.inputs.tag }}"
          else
            CURRENT_TAG="${GITHUB_REF#refs/tags/}"
          fi

          if [ -z "$CURRENT_TAG" ]; then
            echo "Release tag is required. Provide workflow_dispatch input 'tag'."
            exit 1
          fi

          if [[ "$CURRENT_TAG" != v* ]]; then
            echo "Release tag must start with 'v' (example: v1.19.1)."
            exit 1
          fi

          echo "value=$CURRENT_TAG" >> "$GITHUB_OUTPUT"

      - name: Check if release exists
        id: check_release
        run: |
          CURRENT_TAG="${{ steps.current_tag.outputs.value }}"
          if gh release view "$CURRENT_TAG" &>/dev/null; then
            echo "exists=true" >> $GITHUB_OUTPUT
            echo "Release $CURRENT_TAG already exists, skipping creation"
          else
            echo "exists=false" >> $GITHUB_OUTPUT
          fi
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Get previous tag
        if: steps.check_release.outputs.exists == 'false'
        id: prev_tag
        run: |
          CURRENT_TAG="${{ steps.current_tag.outputs.value }}"

          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            PREV_TAG=$(git tag --sort=-v:refname | grep '^v' | grep -vx "$CURRENT_TAG" | head -1 || true)
          else
            PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
          fi

          echo "tag=${PREV_TAG}" >> $GITHUB_OUTPUT

      - name: Generate changelog
        if: steps.check_release.outputs.exists == 'false'
        id: changelog
        run: |
          CURRENT_TAG="${{ steps.current_tag.outputs.value }}"
          PREV_TAG="${{ steps.prev_tag.outputs.tag }}"
          
          echo "## What's New" > changelog.md
          echo "" >> changelog.md
          echo "This release includes updates and fixes shipped with ${CURRENT_TAG}." >> changelog.md
          echo "" >> changelog.md
          echo "### Highlights" >> changelog.md
          echo "" >> changelog.md
          
          if [ -n "$PREV_TAG" ]; then
            echo "Changes from ${PREV_TAG} to ${CURRENT_TAG}:" >> changelog.md
            git log ${PREV_TAG}..${CURRENT_TAG} --pretty=format:"- %s (%h)" --no-merges >> changelog.md
          else
            echo "Recent shipped commits:" >> changelog.md
            git log -20 --pretty=format:"- %s (%h)" --no-merges >> changelog.md
          fi
          
          echo "" >> changelog.md
          echo "" >> changelog.md
          echo "## Docker Images" >> changelog.md
          echo "" >> changelog.md
          echo '```bash' >> changelog.md
          echo "docker pull ghcr.io/${{ github.repository_owner }}/medassist-ng-backend:${CURRENT_TAG#v}" >> changelog.md
          echo "docker pull ghcr.io/${{ github.repository_owner }}/medassist-ng-frontend:${CURRENT_TAG#v}" >> changelog.md
          echo '```' >> changelog.md
          echo "" >> changelog.md
          echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${CURRENT_TAG}" >> changelog.md

      - name: Create GitHub Release
        if: steps.check_release.outputs.exists == 'false'
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.current_tag.outputs.value }}
          target_commitish: ${{ github.sha }}
          body_path: changelog.md
          generate_release_notes: false
          draft: false
          prerelease: ${{ contains(github.ref, '-rc') || contains(github.ref, '-beta') || contains(github.ref, '-alpha') }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
