name: Build and Deploy Wing-Demo

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '24'

      - name: Configure npm registry
        run: |
          echo "registry=https://nexus.gc-si.dev/repository/npm-public/" > frontend/.npmrc
          echo "//nexus.gc-si.dev/repository/npm-public/:_auth=${{ secrets.NEXUS_NPM_AUTH }}" >> frontend/.npmrc
          echo "legacy-peer-deps=true" >> frontend/.npmrc
          echo "registry=https://nexus.gc-si.dev/repository/npm-public/" > backend/.npmrc
          echo "//nexus.gc-si.dev/repository/npm-public/:_auth=${{ secrets.NEXUS_NPM_AUTH }}" >> backend/.npmrc

      # ── Frontend ──
      - name: Install frontend dependencies
        run: |
          cd frontend
          npm ci

      - name: Build frontend
        env:
          VITE_API_URL: /api
          VITE_GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
          VITE_DATA_GO_KR_API_KEY: ${{ secrets.DATA_GO_KR_API_KEY }}
          VITE_WEATHER_API_KEY: ${{ secrets.WEATHER_API_KEY }}
        run: |
          cd frontend
          npx vite build

      - name: Deploy frontend
        run: |
          rm -rf /deploy/wing-demo/*
          cp -r frontend/dist/* /deploy/wing-demo/
          echo "Frontend deployed at $(date '+%Y-%m-%d %H:%M:%S')"

      # ── Backend ──
      - name: Install backend dependencies
        run: |
          cd backend
          npm ci

      - name: Build backend
        run: |
          cd backend
          npx tsc

      - name: Prune dev dependencies
        run: |
          cd backend
          npm prune --omit=dev

      - name: Deploy backend
        run: |
          mkdir -p /deploy/wing-demo-backend/dist
          cp -r backend/dist/* /deploy/wing-demo-backend/dist/
          cp -r backend/node_modules /deploy/wing-demo-backend/
          cp backend/package.json /deploy/wing-demo-backend/
          date '+%s' > /deploy/wing-demo-backend/.deploy-trigger
          echo "Backend deployed at $(date '+%Y-%m-%d %H:%M:%S')"
