name: Release

on:
  release:
    types: [created]

permissions:
  contents: write

jobs:
  release:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          ref: ${{ github.event.release.tag_name }}

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: "24"
          cache: "npm"

      - name: Install dependencies
        run: npm ci --ignore-scripts

      - name: Update package.json version
        run: |
          TAG_VERSION="${{ github.event.release.tag_name }}"
          VERSION="${TAG_VERSION#v}"
          npm version "$VERSION" --no-git-tag-version

      - name: Run type checking
        run: npm run check

      - name: Run linting
        run: npm run lint

      - name: Run unit tests
        run: npm run test:unit -- --run
        env:
          DATABASE_URL: "postgresql://test:test@localhost:5432/test"
          SMTP_HOST: "smtp.example.com"
          SMTP_PORT: "587"
          SMTP_SECURE: "false"
          SMTP_USER: "your-email@example.com"
          SMTP_PASS: "your-password"
          SMTP_FROM_NAME: "Open Reception"
          SMTP_FROM_EMAIL: "noreply@example.com"
          JWT_SECRET: "test"
          MANAGEMENT_DOMAIN: "example.com"

      - name: Build application
        run: npm run build
        env:
          DATABASE_URL: "postgresql://test:test@localhost:5432/test"
          JWT_SECRET: "build"
          MANAGEMENT_DOMAIN: "example.com"

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          platforms: linux/amd64,linux/arm64
          tags: |
            openreception/open-reception:latest
            openreception/open-reception:${{ github.ref_name }}

      - name: Commit and push version update
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add package.json package-lock.json
          git commit -m "chore: bump version to ${{ github.event.release.tag_name }}"
          git push origin HEAD:main
