name: Chore App Build, Test, and Push Docker Images
run-name: ${{ gitea.actor }} is building Chores [${{ gitea.ref_name }}@${{ gitea.sha }}] 🚀
on:
  push:
    branches:
      - master
      - next

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository code
        uses: actions/checkout@v3

      - name: Determine Image Tag
        id: vars
        run: |
          version=$(python -c "import sys; sys.path.append('./backend'); from config.version import BASE_VERSION; print(BASE_VERSION)")
          current_date=$(date +%Y%m%d)
          if [ "${{ gitea.ref }}" == "refs/heads/master" ]; then
            echo "tag=$version" >> $GITHUB_OUTPUT
          else
            echo "tag=next-$version-$current_date" >> $GITHUB_OUTPUT
          fi

      - name: Set up Python for backend tests
        uses: actions/setup-python@v4
        with:
          python-version: "3.11"

      - name: Install backend dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r backend/requirements.txt

      - name: Run backend unit tests
        run: |
          cd backend
          pytest -q

      - name: Set up Node.js for frontend tests
        uses: actions/setup-node@v4
        with:
          node-version: "20.19.0"
          cache: "npm"
          cache-dependency-path: frontend/vue-app/package-lock.json

      - name: Install frontend dependencies
        run: npm ci
        working-directory: frontend/vue-app

      - name: Run frontend unit tests
        run: npm run test:unit --if-present
        working-directory: frontend/vue-app

      - name: Build Backend Docker Image
        run: |
          docker build -t git.ryankegel.com:3000/kegel/chores/backend:${{ steps.vars.outputs.tag }} ./backend

      - name: Build Frontend Docker Image
        run: |
          docker build -t git.ryankegel.com:3000/kegel/chores/frontend:${{ steps.vars.outputs.tag }} ./frontend/vue-app

      - name: Log in to Registry
        uses: docker/login-action@v2
        with:
          registry: git.ryankegel.com:3000
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Push Backend Image to Gitea Registry
        run: |
          for i in {1..3}; do
            echo "Attempt $i to push backend image..."
            if docker push git.ryankegel.com:3000/kegel/chores/backend:${{ steps.vars.outputs.tag }}; then
              echo "Backend push succeeded on attempt $i"
              break
            else
              echo "Backend push failed on attempt $i"
              if [ $i -lt 3 ]; then
                sleep 10
              else
                exit 1
              fi
            fi
          done
          if [ "${{ gitea.ref }}" == "refs/heads/master" ]; then
            docker tag git.ryankegel.com:3000/kegel/chores/backend:${{ steps.vars.outputs.tag }} git.ryankegel.com:3000/kegel/chores/backend:latest
            docker push git.ryankegel.com:3000/kegel/chores/backend:latest
          elif [ "${{ gitea.ref }}" == "refs/heads/next" ]; then
            docker tag git.ryankegel.com:3000/kegel/chores/backend:${{ steps.vars.outputs.tag }} git.ryankegel.com:3000/kegel/chores/backend:next
            docker push git.ryankegel.com:3000/kegel/chores/backend:next
          fi

      - name: Push Frontend Image to Gitea Registry
        run: |
          for i in {1..3}; do
            echo "Attempt $i to push frontend image..."
            if docker push git.ryankegel.com:3000/kegel/chores/frontend:${{ steps.vars.outputs.tag }}; then
              echo "Frontend push succeeded on attempt $i"
              break
            else
              echo "Frontend push failed on attempt $i"
              if [ $i -lt 3 ]; then
                sleep 10
              else
                exit 1
              fi
            fi
          done
          if [ "${{ gitea.ref }}" == "refs/heads/master" ]; then
            docker tag git.ryankegel.com:3000/kegel/chores/frontend:${{ steps.vars.outputs.tag }} git.ryankegel.com:3000/kegel/chores/frontend:latest
            docker push git.ryankegel.com:3000/kegel/chores/frontend:latest
          elif [ "${{ gitea.ref }}" == "refs/heads/next" ]; then
            docker tag git.ryankegel.com:3000/kegel/chores/frontend:${{ steps.vars.outputs.tag }} git.ryankegel.com:3000/kegel/chores/frontend:next
            docker push git.ryankegel.com:3000/kegel/chores/frontend:next
          fi

      - name: Deploy Test Environment
        if: gitea.ref == 'refs/heads/next'
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.DEPLOY_TEST_HOST }}
          username: ${{ secrets.DEPLOY_TEST_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          port: 22
          script: |
            cd /tmp
            if [ -d "chore" ]; then
              cd chore
              git pull origin next || true
            else
              git clone --branch next https://git.ryankegel.com/ryan/chore.git
              cd chore
            fi

            # Write .env file — docker-compose automatically reads this
            cat > .env << EOF
            SECRET_KEY=${{ secrets.SECRET_KEY }}
            REFRESH_TOKEN_EXPIRY_DAYS=1
            DIGEST_TOKEN_SECRET=${{ secrets.DIGEST_TOKEN_SECRET }}
            VAPID_PUBLIC_KEY=${{ secrets.VAPID_PUBLIC_KEY }}
            VAPID_PRIVATE_KEY=${{ secrets.VAPID_PRIVATE_KEY }}
            SEED_EMAIL=${{ secrets.SEED_EMAIL }}
            SEED_PASSWORD=${{ secrets.SEED_PASSWORD }}
            SEED_PIN=${{ secrets.SEED_PIN }}
            SEED_FIRST_NAME=${{ secrets.SEED_FIRST_NAME }}
            SEED_LAST_NAME=${{ secrets.SEED_LAST_NAME }}
            EOF

            echo "SECRET_KEY is set: $(grep -q 'SECRET_KEY=' .env && echo YES || echo NO)"

            echo "Bringing down previous test environment..."
            docker-compose -f docker-compose.test.yml down --volumes --remove-orphans || true
            echo "Starting new test environment..."
            docker-compose -f docker-compose.test.yml pull
            docker-compose -f docker-compose.test.yml up -d

            echo "Waiting for backend to be ready..."
            sleep 10
            echo "Seeding test user..."
            docker-compose -f docker-compose.test.yml exec -T chores-test-app-backend python scripts/seed_test_user.py

      - name: Send mail
        if: always() # Runs on success or failure
        uses: dawidd6/action-send-mail@v3
        with:
          server_address: smtp.gmail.com
          server_port: 465
          username: ${{ secrets.MAIL_USER }}
          password: ${{ secrets.MAIL_PASSWORD }}
          secure: true
          to: ${{ secrets.MAIL_TO }}
          from: Gitea <git@git.ryankegel.com>
          subject: ${{ github.repository }} - Job ${{ job.status }}
          convert_markdown: true
          html_body: |
            ### Job ${{ job.status }}

            ${{ github.repository }}: [${{ github.ref }}@${{ github.sha }}](${{ vars.GIT_SERVER }}/${{ github.repository }}/actions)
