name: Build & Push Docker Image

on:
  push:
    branches: [main, master]
    tags: ['v*']
  workflow_dispatch:
    inputs:
      api_url:
        description: 'API URL for frontend build'
        required: false
        default: 'http://ut.khoavo.myds.me:8981/api'
        type: string

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Tools check
        run: |
          echo "Docker: $(docker --version)"
          echo "Git: $(git --version)"

      - name: Checkout
        run: |
          cd /tmp
          rm -rf kv-tube
          git clone https://vndangkhoa:Thieugia19@git.khoavo.myds.me/vndangkhoa/kv-tube.git
          cd kv-tube
          git checkout ${GITEA_SHA:-main}
          echo "Checked out: $(git rev-parse --short HEAD)"

      - name: Login to registry
        run: echo "Thieugia19" | docker login git.khoavo.myds.me -u vndangkhoa --password-stdin

      - name: Build and push
        run: |
          cd /tmp/kv-tube
          SHA_SHORT=$(git rev-parse --short HEAD)
          IMAGE="git.khoavo.myds.me/vndangkhoa/kv-tube"
          TAGS="${IMAGE}:${SHA_SHORT}"
          if [ "${GITEA_REF}" = "refs/heads/main" ] || [ "${GITEA_REF}" = "refs/heads/master" ]; then
            TAGS="${TAGS},${IMAGE}:main"
          fi
          if echo "${GITEA_REF}" | grep -q "refs/tags/v"; then
            VERSION=${GITEA_REF#refs/tags/v}
            TAGS="${TAGS},${IMAGE}:${VERSION},${IMAGE}:latest"
          fi
          echo "Building tags: ${TAGS}"

          TAG_ARGS=""
          IFS=',' read -ra TAG_ARRAY <<< "${TAGS}"
          for tag in "${TAG_ARRAY[@]}"; do
            TAG_ARGS="${TAG_ARGS} -t ${tag}"
          done

          docker build \
            ${TAG_ARGS} \
            --build-arg NEXT_PUBLIC_API_URL=${{ gitea.event.inputs.api_url || 'http://ut.khoavo.myds.me:8981/api' }} \
            .

          for tag in "${TAG_ARRAY[@]}"; do
            echo "Pushing ${tag}..."
            docker push "${tag}"
          done

      - name: Verify
        run: docker images | grep kv-tube

      - name: Cleanup
        if: always()
        run: rm -rf /tmp/kv-tube
