name: Deploy Laravel 12 (OVH Shared)

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      # 1️⃣ Checkout repository
      - name: Checkout repository
        uses: actions/checkout@v4

      # 2️⃣ Deploy file via SFTP (OVH SAFE)
      - name: Deploy files via SFTP
        uses: appleboy/scp-action@v0.1.7
        with:
          host: ${{ secrets.SFTP_HOST }}
          username: ${{ secrets.SFTP_USER }}
          password: ${{ secrets.SFTP_PASS }}
          port: ${{ secrets.SFTP_PORT }}
          source: "*"
          target: /homez.2167/italenr/www
          rm: false
          overwrite: true

      # 3️⃣ Ensure Laravel writable directories and include .gitkeep
      - name: Ensure Laravel writable directories
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SFTP_USER }}
          password: ${{ secrets.SFTP_PASS }}
          port: ${{ secrets.SFTP_PORT }}
          script: |
            cd /homez.2167/italenr/www
            # Create framework folders if missing
            mkdir -p storage/framework/{cache,sessions,views}
            mkdir -p bootstrap/cache
            # Add .gitkeep so folders exist anche se vuote
            touch storage/framework/cache/.gitkeep
            touch storage/framework/sessions/.gitkeep
            touch storage/framework/views/.gitkeep
            touch bootstrap/cache/.gitkeep
            # Set permissions
            chmod -R 775 storage bootstrap/cache

      # 4️⃣ Composer install + Laravel optimize (senza view:cache)
      - name: Composer install & Laravel optimize
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SFTP_USER }}
          password: ${{ secrets.SFTP_PASS }}
          port: ${{ secrets.SFTP_PORT }}
          script: |
            cd /homez.2167/italenr/www
            composer install --no-dev --optimize-autoloader
            php artisan migrate --force
            php artisan view:cache
            php artisan config:clear
            php artisan config:cache
            php artisan route:cache
