name: R Package Tests (SQL Server)

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

jobs:
  test:
    runs-on: ubuntu-latest

    env:
      GITHUB_PAT: ${{ secrets.GH_PAT }}
      SQLSERVER_SERVER: localhost
      SQLSERVER_DBNAME: cdm
      SQLSERVER_USER: sa
      SQLSERVER_PASSWORD: 'TestPass123!'
      SQLSERVER_PORT: 1433

    services:
      mssql:
        image: mcr.microsoft.com/mssql/server:2022-latest
        env:
          ACCEPT_EULA: 'Y'
          MSSQL_SA_PASSWORD: 'TestPass123!'
        ports:
          - 1433:1433
        options: >-
          --health-cmd="/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P 'TestPass123!' -C -Q 'SELECT 1'"
          --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 \
            unixodbc-dev

          curl -fsSL "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb" \
            -o /tmp/packages-microsoft-prod.deb
          sudo dpkg -i /tmp/packages-microsoft-prod.deb

          sudo apt-get update -y
          sudo ACCEPT_EULA=Y apt-get install -y --no-install-recommends \
            msodbcsql18 \
            mssql-tools18

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

      - name: Install package
        run: R CMD INSTALL .

      - name: Create Test Database
        run: |
          /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "TestPass123!" -C -Q "CREATE DATABASE cdm;"

      - name: Run Tests
        run: |
          Rscript -e 'test_results <- suppressWarnings(testthat::test_file("tests/testthat/test-sqlserver.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)'
