name: Build and Deploy to Kubernetes

on:
  push:
    branches: [ main ]
    paths-ignore:
      - 'k8s/**'
  pull_request:
    paths-ignore:
      - 'k8s/**'

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

jobs:
  test:
    runs-on: ubuntu-latest

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

    - name: Install uv
      uses: astral-sh/setup-uv@v7
      with:
        version: "latest"
        python-version: "3.12"
        enable-cache: true

    - name: Install dependencies (including dev)
      run: uv sync --dev

    - name: Run tests
      env:
        DJANGO_SETTINGS_MODULE: core.settings
        FILE_UPLOADS_FOLDER: /tmp/test-uploads
      run: uv run pytest tests/ -v --tb=short

  build-and-deploy:
    runs-on: ubuntu-latest
    needs: test
    if: github.event_name == 'push'
    permissions:
      contents: write
      packages: write

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

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

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v5
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

    - name: Set build timestamp
      id: build_time
      run: echo "value=$(date -u '+%Y-%m-%d %H:%M:%S UTC')" >> $GITHUB_OUTPUT

    # Build and push main application image
    - name: Build and push Docker image
      uses: docker/build-push-action@v6
      with:
        context: .
        file: Dockerfile
        push: true
        tags: |-
          ${{ steps.meta.outputs.tags }}
          ghcr.io/wahyd4/links:1.0.${{ github.run_number }}
        labels: |-
          ${{ steps.meta.outputs.labels }}
        build-args: |-
          BUILD_TIME=${{ steps.build_time.outputs.value }}
          BUILD_VERSION=1.0.${{ github.run_number }}

    - name: Commit updated manifest
      run: |
        # Render template → manifest with the actual image tag
        sed 's|__IMAGE_TAG__|1.0.${{ github.run_number }}|g' k8s/manifest.template.yaml > k8s/manifest.yaml
        git config user.name "github-actions[bot]"
        git config user.email "github-actions[bot]@users.noreply.github.com"
        git add k8s/manifest.yaml
        git commit -m "chore: update manifest image to 1.0.${{ github.run_number }} [skip ci]"
        # Pull any commits pushed since this workflow started, then push
        git pull --rebase origin main
        git push
