name: R Package Tests (PostgreSQL)

on:
  push:
    branches: [develop]
  pull_request:
    branches: [main, develop]

jobs:
  test:
    runs-on: ubuntu-latest

    env:
      GITHUB_PAT: ${{ secrets.GH_PAT }}
      POSTGRESQL_SERVER: localhost
      POSTGRESQL_DBNAME: cdm
      POSTGRESQL_USER: postgres
      POSTGRESQL_PASSWORD: TestPass123!
      POSTGRESQL_PORT: 5432

    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: TestPass123!
          POSTGRES_DB: cdm
        ports:
          - 5432:5432
        options: >-
          --health-cmd="pg_isready -U postgres -d cdm"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=10

    steps:
      - uses: actions/checkout@v4

      - name: Setup R
        uses: r-lib/actions/setup-r@v2
        with:
          r-version: '4.4.1'
          use-public-rspm: true

      - name: Install System Dependencies
        run: |
          set -euxo pipefail

          # GitHub's Ubuntu runner can keep stale package paths behind the
          # mirror+file source. Use the direct Ubuntu archive and refresh lists.
          sudo sed -i 's|mirror+file:/etc/apt/apt-mirrors.txt|http://archive.ubuntu.com/ubuntu/|g' /etc/apt/sources.list.d/ubuntu.sources
          sudo apt-get clean
          sudo rm -rf /var/lib/apt/lists/*

          sudo apt-get update -y
          sudo apt-get install -y --no-install-recommends \
            ca-certificates \
            curl \
            libcurl4-openssl-dev \
            libpq-dev

      - name: Install R dependencies
        uses: r-lib/actions/setup-r-dependencies@v2
        with:
          needs: check

      - name: Install PostgreSQL R driver
        run: |
          Rscript -e 'if (!requireNamespace("RPostgres", quietly = TRUE)) install.packages("RPostgres")'

      - name: Install package
        run: R CMD INSTALL .

      - name: Run Tests
        run: |
          Rscript -e 'test_results <- suppressWarnings(testthat::test_file("tests/testthat/test-postgresql.R")); results <- as.data.frame(test_results); problem_columns <- intersect(c("failed", "failure", "error", "errors"), names(results)); if (length(problem_columns) > 0 && any(results[problem_columns] > 0)) stop("Test failures or errors detected!", call. = FALSE)'
