name: Deploy to dev env on merge

on:
  push:
    branches:
      - dev

env:
  REGISTRY: registry.africarecrut.com
  REGISTRY_USER: ${{ secrets.REGISTRY_DEV_USER }}
  REGISTRY_PWD: ${{ secrets.REGISTRY_DEV_PWD }}

  IMAGE_NAME: africa-recrut-api
  IMAGE_TAG: dev.1.0.51
  NAMESPACE: dev
  CONTAINER_PORT: 3000

  ENVS: ${{ secrets.ENVS_DEV_JSON }}

jobs:
  app_test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Bun
        uses: oven-sh/setup-bun@v1
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install

      - name: Run Tests
        run: bun run test

  docker_build_and_push:
    runs-on: ubuntu-latest
    needs: app_test
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log into registry ${{ env.REGISTRY }}
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ env.REGISTRY_USER }}
          password: ${{ env.REGISTRY_PWD }}

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          push: true
          tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{env.IMAGE_TAG}}

  deploy:
    runs-on: ubuntu-latest
    needs: docker_build_and_push
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up kubectl
        uses: azure/setup-kubectl@v3

      - name: Create .kube directory
        run: mkdir -p $HOME/.kube

      - name: Set up kubeconfig
        run: echo "${{ secrets.KUBECONFIG }}" > $HOME/.kube/config

      - name: Install Jinja2
        run: pip install jinja2

      - name: Render deployment template
        run: |
          python .github/templates/template_builder.py \
            .github/templates/deployment.j2 \
            IMAGE_NAME,IMAGE_TAG,NAMESPACE,REGISTRY,CONTAINER_PORT,ENVS > deployment.yaml

      - name: Render service template
        run: |
          python .github/templates/template_builder.py \
            .github/templates/service.j2 \
            IMAGE_NAME,IMAGE_TAG,NAMESPACE,CONTAINER_PORT > service.yaml

      - name: Apply service
        run: kubectl apply -f service.yaml

      - name: Apply deployment
        run: kubectl apply -f deployment.yaml
