name: K3s Auto-Deploy
on:
  push:
    branches:
      - dev
      - hml
  workflow_dispatch:
    inputs:
      environment:
        description: 'Ambiente para deploy'
        required: true
        default: 'hml'
        type: choice
        options:
          - hml
          - prd

jobs:
  build-and-deploy:
    runs-on: self-hosted
    steps:
      - name: Checkout Code
        run: |
          rm -rf *
          git clone -b dev https://${{ github.actor }}:${{ secrets.FORGEJO_TOKEN }}@git.saveinmed.com.br/${{ github.repository }}.git .

      - name: Build and Push
        run: |
          # Garante que temos o cliente Docker
          apk add --no-cache docker-cli

          export DOCKER_HOST=tcp://localhost:2375
          echo "${{ secrets.FORGEJO_TOKEN }}" | docker login git.saveinmed.com.br -u ${{ github.actor }} --password-stdin

          docker build -t git.saveinmed.com.br/${{ github.repository }}:latest ./backend
          docker push git.saveinmed.com.br/${{ github.repository }}:latest

      - name: Deploy (dev)
        if: github.ref_name == 'dev'
        run: |
          apk add --no-cache curl ca-certificates
          curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
          chmod +x kubectl
          mv kubectl /usr/local/bin/kubectl
          kubectl apply -f k8s/
          kubectl rollout restart deployment/photum-backend -n photum-dev

      - name: Deploy (hml)
        if: github.ref_name == 'hml' || (github.event_name == 'workflow_dispatch' && github.event.inputs.environment == 'hml')
        run: |
          apk add --no-cache curl ca-certificates
          curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
          chmod +x kubectl
          mv kubectl /usr/local/bin/kubectl
          kubectl apply -f k8s/hml/
          kubectl rollout restart deployment/photum-backend -n photum-hml

      - name: Deploy (prd)
        if: github.event_name == 'workflow_dispatch' && github.event.inputs.environment == 'prd'
        run: |
          apk add --no-cache curl ca-certificates
          curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
          chmod +x kubectl
          mv kubectl /usr/local/bin/kubectl
          kubectl apply -f k8s/prd/
          kubectl rollout restart deployment/photum-backend -n photum-prd
