name: CI/CD Pipeline

on:
  push:
    branches:
      - prod
      - test
  workflow_dispatch:

env:
  REGISTRY_URL: mf-image.tencentcloudcr.com
  ENV_TAG: ${{ github.ref_name == 'prod' && 'prod' || 'test' }}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      - name: Set Dynamic Image Name
        run: |
          PROJECT_NAME_RAW=$(echo "${{ github.repository }}" | cut -d'/' -f2)
          echo PROJECT_NAME=$(echo "$PROJECT_NAME_RAW" | tr '_' '-') >> $GITHUB_ENV

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Install Dependencies
        run: npm install -g yarn && yarn install

      - name: Build App
        run: yarn build

      - name: Login Docker Registry
        run: |
          echo "${{ secrets.DOCKER_PASSWORD }}" | docker login $REGISTRY_URL -u ${{ secrets.DOCKER_USERNAME }} --password-stdin

      - name: Build Docker Image
        run: |
          ls  -l
          docker build -t $REGISTRY_URL/$ENV_TAG/${{ env.PROJECT_NAME }}:${{ github.sha }} .

      - name: Push Docker Image
        run: |
          docker push $REGISTRY_URL/$ENV_TAG/${{ env.PROJECT_NAME }}:${{ github.sha }}

  deploy:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Set up kubectl
        uses: azure/setup-kubectl@v3

      - name: Set Dynamic Image Name
        run: |
          PROJECT_NAME_RAW=$(echo "${{ github.repository }}" | cut -d'/' -f2)
          echo PROJECT_NAME=$(echo "$PROJECT_NAME_RAW" | tr '_' '-') >> $GITHUB_ENV

      - name: Set up Kubeconfig
        run: |
          mkdir -p ~/.kube
          echo '${{ secrets.KUBE_CONFIG }}' > ~/.kube/config

      - name: Deploy to Kubernetes
        run: |
          kubectl -n $ENV_TAG set image deployment/${{ env.PROJECT_NAME }} \
            ${{ env.PROJECT_NAME }}=$REGISTRY_URL/$ENV_TAG/${{ env.PROJECT_NAME }}:${{ github.sha }}
