name: Build and deploy theme to environment server using SFTP

on:
  push:
    branches: [prd, stg]
    paths:
      - 'wp-content/themes/**'
  workflow_dispatch:

env:
  THEME: filmspourenfants

permissions:
  contents: read
  pages: write
  id-token: write

jobs:
  composer:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'

      - uses: ramsey/composer-install@v2
        with:
          working-directory: ./wp-content/themes/${{ env.THEME }}/

      - name: Run linting
        working-directory: ./wp-content/themes/${{ env.THEME }}/
        run: |
          composer run-script lint:php
          composer run-script lint:wpcs

  node-build:
    runs-on: ubuntu-latest

    defaults:
      run:
        working-directory: ./wp-content/themes/${{ env.THEME }}/

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: "npm"
          cache-dependency-path: ./wp-content/themes/${{ env.THEME }}/package-lock.json

      - run: npm ci
      - run: npm run build

      - name: Upload build files
        uses: actions/upload-artifact@v4
        with:
          name: build-files
          path: "wp-content/themes/${{ env.THEME }}/build/"

  deploy:
    needs: [composer, node-build]

    runs-on: ubuntu-latest

    environment:
      name: ${{ github.ref_name }}

    defaults:
      run:
        working-directory: ./

    steps:
      - uses: actions/checkout@v4

      - uses: actions/download-artifact@v4
        with:
          name: build-files
          path: "wp-content/themes/${{ env.THEME }}/build/"

      - uses: wlixcc/SFTP-Deploy-Action@v1.2.6
        with:
          username: ${{ secrets.SFTP_USERNAME }}
          server: ${{ secrets.SFTP_SERVER }}
          port: ${{ secrets.SFTP_PORT }}
          password: ${{ secrets.SFTP_PASSWORD }}
          local_path: 'wp-content/themes/${{ env.THEME }}/*'
          remote_path: '${{ secrets.SFTP_PATH }}/wp-content/themes/${{ env.THEME }}'
          delete_remote_files: true
