name: CI

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

concurrency:
  group: ci-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  test:
    name: Go tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version: "1.25"
          cache: true

      - name: Run unit tests
        run: go test ./...

  integration:
    name: Integration tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version: "1.25"
          cache: true

      - name: Run integration tests
        env:
          ULTI_TEST_INTEGRATION: "1"
          MAIL_CREDENTIAL_KEYS: "v1:MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY="
          MAIL_ACTIVE_CREDENTIAL_KEY_ID: "v1"
          MAIL_WEBHOOK_SHARED_SECRET: "test-webhook-secret"
          NEXTCLOUD_ENABLED: "false"
          IMMICH_ENABLED: "false"
          JITSI_ENABLED: "false"
        run: go test -tags=integration ./internal/integrationtest/... -count=1 -timeout=10m

  migrations:
    name: DB migrations
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: ulti
          POSTGRES_PASSWORD: test
          POSTGRES_DB: ultidb
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U ulti -d ultidb"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4

      - name: Install golang-migrate
        run: |
          curl -fsSL https://github.com/golang-migrate/migrate/releases/download/v4.18.1/migrate.linux-amd64.tar.gz | tar xz migrate
          sudo install migrate /usr/local/bin/migrate
          migrate -version

      - name: Verify migrations (up → down → up)
        env:
          DATABASE_URL: postgres://ulti:test@localhost:5432/ultidb?sslmode=disable
        run: |
          set -euo pipefail
          migrate -path migrations -database "$DATABASE_URL" up
          migrate -path migrations -database "$DATABASE_URL" down -all
          migrate -path migrations -database "$DATABASE_URL" up
