---
- name: Déployer Backend Go
  hosts: edge
  become: true
  
  tasks:
    - name: Installer Go et dépendances
      command: |
        incus exec veza-backend -- bash -c 'apt update && apt install -y wget git build-essential'

    - name: Télécharger et installer Go
      command: |
        incus exec veza-backend -- bash -c '
          cd /tmp
          wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz
          tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz
          echo "export PATH=\$PATH:/usr/local/go/bin" >> /root/.bashrc
        '

    - name: Créer l'application Backend
      command: |
        incus exec veza-backend -- bash -c 'cat > /opt/backend.go << EOF
        package main
        
        import (
            "encoding/json"
            "log"
            "net/http"
            "os"
        )
        
        func main() {
            port := os.Getenv("PORT")
            if port == "" { port = "8080" }
        
            http.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
                w.Header().Set("Content-Type", "application/json")
                json.NewEncoder(w).Encode(map[string]string{
                    "status": "ok",
                    "service": "veza-backend",
                    "version": "1.0.0",
                })
            })
        
            http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
                w.Header().Set("Content-Type", "application/json")
                json.NewEncoder(w).Encode(map[string]string{
                    "message": "Veza V5 Ultra Backend API",
                    "version": "1.0.0",
                    "endpoint": r.URL.Path,
                })
            })
        
            log.Printf("Backend starting on :%s", port)
            http.ListenAndServe(":"+port, nil)
        }
        EOF'

    - name: Compiler le backend
      command: |
        incus exec veza-backend -- bash -c '
          cd /opt
          /usr/local/go/bin/go mod init veza-backend
          /usr/local/go/bin/go build -o veza-backend backend.go
        '

    - name: Créer le service systemd
      command: |
        incus exec veza-backend -- bash -c 'cat > /etc/systemd/system/veza-backend.service << EOF
        [Unit]
        Description=Veza Backend API
        After=network.target
        
        [Service]
        Type=simple
        ExecStart=/opt/veza-backend
        Restart=always
        Environment=PORT=8080
        
        [Install]
        WantedBy=multi-user.target
        EOF'

    - name: Démarrer le service
      command: |
        incus exec veza-backend -- systemctl daemon-reload
        incus exec veza-backend -- systemctl enable veza-backend
        incus exec veza-backend -- systemctl start veza-backend
