#!/usr/bin/env bash
##############################################################
# GMLM Platform — GitLab Repository Push Script
#
# Usage:
#   bash scripts/push-to-gitlab.sh \
#     --token  glpat-XXXXXXXXXXXXXXXXXXXX \
#     --repo   your-group/gmlm-platform \
#     --gitlab https://gitlab.com \
#     [--create-repo]
##############################################################

set -euo pipefail

GITLAB_TOKEN=""
REPO=""
GITLAB_URL="https://gitlab.com"
BRANCH="main"
CREATE_REPO=false

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --token)       GITLAB_TOKEN="$2"; shift ;;
        --repo)        REPO="$2";         shift ;;
        --gitlab)      GITLAB_URL="$2";   shift ;;
        --branch)      BRANCH="$2";       shift ;;
        --create-repo) CREATE_REPO=true   ;;
        *) echo "Unknown: $1"; exit 1 ;;
    esac
    shift
done

if [[ -z "$GITLAB_TOKEN" || -z "$REPO" ]]; then
    echo "Error: --token and --repo are required."
    exit 1
fi

NAMESPACE=$(echo "$REPO" | cut -d'/' -f1)
PROJECT=$(echo "$REPO" | cut -d'/' -f2)

echo "▶ Pushing GMLM to GitLab: ${GITLAB_URL}/${REPO}..."

# ── Create repo if needed ─────────────────────────────────────
if [[ "$CREATE_REPO" == "true" ]]; then
    NAMESPACE_ID=$(curl -sf \
        -H "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
        "${GITLAB_URL}/api/v4/namespaces?search=${NAMESPACE}" \
        | jq -r '.[0].id // ""')

    curl -sf -X POST \
        -H "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
        -H "Content-Type: application/json" \
        "${GITLAB_URL}/api/v4/projects" \
        -d "{\"name\": \"${PROJECT}\", \"namespace_id\": \"${NAMESPACE_ID}\", \"visibility\": \"private\"}" \
        > /dev/null
    echo "✓ GitLab repository created."
fi

# ── Push via git ──────────────────────────────────────────────
cd "$(git rev-parse --show-toplevel 2>/dev/null || echo .)"
[[ ! -d ".git" ]] && git init && git checkout -b "${BRANCH}" 2>/dev/null || true

git config user.email "gmlm-deploy@globalmlmsoftware.com" 2>/dev/null || true
git config user.name "GMLM Deploy" 2>/dev/null || true
git add -A
git commit -m "feat: GMLM Platform — enterprise MLM SaaS" --allow-empty -q

REMOTE_URL="${GITLAB_URL}/${REPO}.git"
# Inject token into URL for auth
AUTH_URL=$(echo "$REMOTE_URL" | sed "s|https://|https://oauth2:${GITLAB_TOKEN}@|")

git remote remove origin 2>/dev/null || true
git remote add origin "${AUTH_URL}"
git push origin "${BRANCH}" --force 2>&1 | grep -v "oauth2"

echo ""
echo "✓ GMLM pushed to GitLab: ${GITLAB_URL}/${REPO}"
echo "  Branch: ${BRANCH}"
echo ""
echo "  Clone with:"
echo "  git clone ${GITLAB_URL}/${REPO}.git"
