#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
INFRA_DIR="$SCRIPT_DIR/.."

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

DOMAIN="${1:-wixur.ir}"
TAG="${2:-latest}"
DOCKER_USERNAME="${DOCKER_USERNAME:-dyolink}"
PUBLIC_BASE="https://${DOMAIN}"

echo -e "${BLUE}Building Dyolink images for ${PUBLIC_BASE}${NC}"
echo -e "${YELLOW}Docker Hub: ${DOCKER_USERNAME}/dyolink-*:${TAG}${NC}"

if ! docker info >/dev/null 2>&1; then
  echo "Docker is not running."
  exit 1
fi

echo -e "${YELLOW}Ensure you are logged in: docker login${NC}"

docker build \
  -t "${DOCKER_USERNAME}/dyolink-backend:${TAG}" \
  -t "${DOCKER_USERNAME}/dyolink-backend:latest" \
  "${REPO_ROOT}/backend"

docker build \
  --build-arg "NEXT_PUBLIC_API_URL=${PUBLIC_BASE}/api" \
  --build-arg "NEXT_PUBLIC_APP_URL=${PUBLIC_BASE}" \
  --build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" \
  -t "${DOCKER_USERNAME}/dyolink-frontend:${TAG}" \
  -t "${DOCKER_USERNAME}/dyolink-frontend:latest" \
  "${REPO_ROOT}/frontend"

docker push "${DOCKER_USERNAME}/dyolink-backend:${TAG}"
docker push "${DOCKER_USERNAME}/dyolink-backend:latest"
docker push "${DOCKER_USERNAME}/dyolink-frontend:${TAG}"
docker push "${DOCKER_USERNAME}/dyolink-frontend:latest"

echo -e "${GREEN}Pushed:${NC}"
echo "  ${DOCKER_USERNAME}/dyolink-backend:${TAG}"
echo "  ${DOCKER_USERNAME}/dyolink-frontend:${TAG}"
