when:
  - branch:
      - main
      - stand-alone
    event: push

steps:

  # Etape 1 : Build de l'application statique
  - name: build
    image: node:20-alpine
    environment:
      NODE_ENV: production
      HUSKY: 0
      HUSKY_SKIP_INSTALL: 1
    commands:
      - apk add --no-cache git python3
      - npm ci --legacy-peer-deps
      - cd radar-app && npm ci --legacy-peer-deps --include=dev && npm run build:icons && cd ..
      - node scripts/generate-team-visualization-data.js
      - npm run build
      - ls -la build/ | head -10

  # Etape 2a : Deploiement via rsync (optionnel — choisir rsync OU docker, pas les deux)
  - name: deploy-rsync
    image: alpine:latest
    environment:
      DEPLOY_HOST:
        from_secret: deploy_host
      DEPLOY_USER:
        from_secret: deploy_user
      DEPLOY_PATH:
        from_secret: deploy_path
      DEPLOY_KEY:
        from_secret: deploy_key
    commands:
      - apk add --no-cache openssh-client rsync
      - mkdir -p ~/.ssh
      - echo "$DEPLOY_KEY" > ~/.ssh/id_rsa
      - chmod 600 ~/.ssh/id_rsa
      - ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts || true
      - rsync -avz --delete build/ $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH/
      - echo "Deploiement termine sur $DEPLOY_HOST:$DEPLOY_PATH"

  # Etape 2b : Deploiement via Docker Compose (recommande)
  - name: deploy-docker
    image: docker:27-cli
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    commands:
      - docker compose -f docker-compose.business.yml build --no-cache
      - docker compose -f docker-compose.business.yml up -d --remove-orphans
      - docker compose -f docker-compose.business.yml ps | grep laplank-radar || echo "Conteneur non trouve"

  # Etape 3 : Notification Telegram
  - name: notify
    image: appleboy/drone-telegram
    settings:
      token:
        from_secret: telegram_token
      to:
        from_secret: telegram_chat_id_ajr
      format: markdown
      message: >
        {{#success build.status}}
        ✅ Build réussi pour `{{repo.name}}` sur la branche `{{commit.branch}}`
        📝 Commit: `{{commit.message}}`
        👤 Auteur: {{commit.author}}
        🔗 {{ build.link }}
        {{else}}
        ❌ Build échoué pour `{{repo.name}}` sur la branche `{{commit.branch}}`
        📝 Commit: `{{commit.message}}`
        👤 Auteur: {{commit.author}}
        🔗 {{ build.link }}
        {{/success}}
    when:
      - status:
          - success
          - failure
