name: Facebook Marketing Service CI

on:
  push:
    paths:
      - 'services/mkt-facebook-service-net/**'
  pull_request:
    paths:
      - 'services/mkt-facebook-service-net/**'

permissions:
  contents: read

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16-alpine
        env:
          POSTGRES_USER: testuser
          POSTGRES_PASSWORD: testpass
          POSTGRES_DB: test_db
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432

    steps:
      - uses: actions/checkout@v4

      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0.x'

      - name: Restore API project
        run: dotnet restore services/mkt-facebook-service-net/src/FacebookService.API/FacebookService.API.csproj

      - name: Build API project
        run: dotnet build services/mkt-facebook-service-net/src/FacebookService.API/FacebookService.API.csproj --configuration Release --no-restore


      - name: Restore dotnet tools
        run: dotnet tool restore

      - name: Generate OpenAPI spec
        run: bash scripts/ci/generate-openapi.sh services/mkt-facebook-service-net FacebookService.API

      - name: Upload OpenAPI spec artifact
        uses: actions/upload-artifact@v4
        with:
          name: openapi-facebookservice-api
          path: services/mkt-facebook-service-net/openapi.yaml
          if-no-files-found: warn
      - name: Restore test projects
        run: |
          dotnet restore services/mkt-facebook-service-net/tests/FacebookService.UnitTests/FacebookService.UnitTests.csproj
          dotnet restore services/mkt-facebook-service-net/tests/FacebookService.FunctionalTests/FacebookService.FunctionalTests.csproj

      - name: Run unit tests with coverage
        run: >
          dotnet test services/mkt-facebook-service-net/tests/FacebookService.UnitTests/FacebookService.UnitTests.csproj
          --configuration Release --no-restore --verbosity normal
          --collect:"XPlat Code Coverage"
          --settings coverage.runsettings
          --results-directory TestResults/unit

      - name: Run functional tests
        run: dotnet test services/mkt-facebook-service-net/tests/FacebookService.FunctionalTests/FacebookService.FunctionalTests.csproj --configuration Release --no-restore --verbosity normal
        env:
          ConnectionStrings__DefaultConnection: Host=localhost;Port=5432;Database=test_db;Username=testuser;Password=testpass
          ASPNETCORE_ENVIRONMENT: Testing

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v4
        with:
          files: TestResults/unit/**/coverage.cobertura.xml
          flags: mkt_facebook_service_net
          fail_ci_if_error: false
        env:
          CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
