name: IT Nexus Deploy

on:
  push:
    branches:
      - main
  workflow_dispatch:
    inputs:
      deploy:
        description: 'Manuell deployen?'
        required: true
        default: 'yes'

jobs:
  build:
    name: Build Frontend
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js 18
        uses: actions/setup-node@v4
        with:
          node-version: '18'
          cache: 'npm'
          cache-dependency-path: frontend/package-lock.json

      - name: Install dependencies
        working-directory: frontend
        run: npm install

      - name: Build frontend
        working-directory: frontend
        run: npm run build
        env:
          CI: false

  deploy:
    name: Deploy to Production
    runs-on: ubuntu-latest
    needs: build
    environment: production
    if: github.event_name == 'workflow_dispatch'

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup SSH key
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H ${{ secrets.SERVER_IP }} >> ~/.ssh/known_hosts

      - name: Deploy frontend/src to server
        run: |
          scp -r frontend/src root@${{ secrets.SERVER_IP }}:/opt/it-nexus/frontend/src

      - name: Deploy backend/src to server
        run: |
          scp -r backend/src root@${{ secrets.SERVER_IP }}:/opt/it-nexus/backend/src

      - name: Rebuild and restart Docker containers
        run: |
          ssh root@${{ secrets.SERVER_IP }} "cd /opt/it-nexus && docker compose build frontend backend && docker compose up -d frontend backend"
