name: Deploy

on:
  push:
    branches:
      - main

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

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'

      - name: Install Node.js dependencies
        run: npm ci

      - name: Run ESLint
        run: npm run lint

      - name: Setup Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          profile: minimal

      - name: Cache Rust dependencies
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            markdown_backend/target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-

      - name: Check Rust code
        working-directory: markdown_backend
        run: cargo check

      - name: Install Docker
        uses: docker/setup-buildx-action@v2

      - name: Build Docker image
        run: docker build -t localhost:3002/rattatwinko/markdownblog:latest .

      - name: Save Docker image as tarball
        run: docker save localhost:3002/rattatwinko/markdownblog:latest -o markdownblog-image.tar

      - name: Upload Docker image artifact
        uses: actions/upload-artifact@v3
        with:
          name: markdownblog-docker-image
          path: markdownblog-image.tar

      - name: Push Docker image
        run: docker push localhost:3002/rattatwinko/markdownblog:latest
