name: CI

on:
  push:
    branches:
      - main

  pull_request:
    branches:
      - main

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install pnpm
        uses: pnpm/action-setup@v4
        with:
          run_install: false

      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Lint
        run: pnpm run lint

  typecheck:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install pnpm
        uses: pnpm/action-setup@v4
        with:
          run_install: false

      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Typecheck
        run: pnpm run typecheck

  build:
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4
      
      # 1. 登录 registry
      - name: Login to private registry
        uses: docker/login-action@v3
        with:
          registry: reg.lijue.net:5888
          username: ${{ secrets.REGISTRY_USER }}       # 在仓库里事先存好
          password: ${{ secrets.REGISTRY_PASSWORD }}
 
      # 2. 构建并推送
      - name: Build & push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: reg.lijue.net:5888/docs/docs:latest

      - name: Trigger Coolify deploy
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        env:
          COOLIFY_API_URL: https://coolify.lijue.net:5888/api/v1/deploy?uuid=ks44swgo4kc8wgwkwck4s004&force=false
          COOLIFY_TOKEN: ${{ secrets.COOLIFY_TOKEN }}
        run: |
          set -euo pipefail
          echo "Triggering Coolify deploy: $COOLIFY_API_URL"
          http_code=$(curl -sS -w "%{http_code}" -o coolify_response.json -X GET "$COOLIFY_API_URL" \
            -H "Authorization: Bearer $COOLIFY_TOKEN" \
            -H "Accept: application/json")
          echo "HTTP status: $http_code"
          echo "Response:"
          cat coolify_response.json
          if [ "$http_code" -lt 200 ] || [ "$http_code" -ge 400 ]; then
            echo "Coolify deploy trigger failed"
            exit 1
          fi