name: build-and-deploy

on:
  push:
    branches: [ main, master ]

jobs:
  build-and-deploy:
    runs-on: docker
    env:
      REG: ${{ vars.REGISTRY_URL }}
      REPO_OWNER: ${{ github.repository_owner }}
      APP_NAME: ${{ vars.APP_NAME }}
      APP_DOMAIN: ${{ vars.APP_DOMAIN }}
      # Printer configuration
      PRINTER_HOST: ${{ vars.PRINTER_HOST }}
      PRINTER_DEVICE_ID: ${{ vars.PRINTER_DEVICE_ID }}
      PRINTER_TIMEOUT_MS: ${{ vars.PRINTER_TIMEOUT_MS }}
      # Authentik configuration
      NUXT_PUBLIC_AUTHENTIK_URL: ${{ vars.NUXT_PUBLIC_AUTHENTIK_URL }}
      NUXT_PUBLIC_AUTH_ENABLED: ${{ vars.NUXT_PUBLIC_AUTH_ENABLED }}
      # MCP Server authentication
      MCP_AUTH_TOKEN: ${{ secrets.MCP_AUTH_TOKEN }}
    steps:
      - name: Build, Push and Deploy
        run: |
          set -e

          echo "=== Checkout ==="
          git clone --depth 1 ${{ github.server_url }}/${{ github.repository }}.git repo
          cd repo

          echo "=== Setup Docker Buildx ==="
          docker buildx create --use --name builder || docker buildx use builder

          echo "=== Login to Registry ==="
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ vars.REGISTRY_URL }} -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin

          echo "=== Build and Push Image ==="
          docker build -t $REG/${{ github.repository_owner }}/$APP_NAME:${{ github.sha }} -t $REG/${{ github.repository_owner }}/$APP_NAME:latest .
          docker push $REG/${{ github.repository_owner }}/$APP_NAME:${{ github.sha }}
          docker push $REG/${{ github.repository_owner }}/$APP_NAME:latest

          echo "=== Deploy Info ==="
          echo "Deploying $APP_NAME"
          echo "  Domain: $APP_DOMAIN"
          echo "  Image: $REG/${{ github.repository_owner }}/$APP_NAME:latest"
          echo "  Network: principal"

          echo "=== Pull Fresh Images ==="
          docker compose pull || true

          echo "=== Clean Up Stack ==="
          docker compose --project-name $APP_NAME down || true

          echo "=== Update Stack ==="
          docker compose --project-name $APP_NAME up -d --remove-orphans --wait

          echo "=== Deployment Complete ==="
