#!/bin/bash
set -euo pipefail

ENV_NAME=$1  # "staging" or "test"
APP_PORT=$2  # 3001 or 3002
REPO_DIR="/opt/church-website/repo"
ENV_DIR="/opt/church-website/envs/${ENV_NAME}"
CONTAINER_NAME="app-${ENV_NAME}"
IMAGE_NAME="church-website:${ENV_NAME}"
MIGRATE_IMAGE="church-website-migrate:${ENV_NAME}"
NETWORK_NAME="church-website-net"

if [ ! -f "${ENV_DIR}/.env" ]; then
  echo "Error: ${ENV_DIR}/.env not found"
  exit 1
fi

echo "==> Building app image ${IMAGE_NAME}..."
docker build \
  --build-arg NEXT_PUBLIC_SERVER_URL="$(grep NEXT_PUBLIC_SERVER_URL "${ENV_DIR}/.env" | cut -d= -f2-)" \
  --build-arg NEXT_PUBLIC_SITE_ID="$(grep NEXT_PUBLIC_SITE_ID "${ENV_DIR}/.env" | cut -d= -f2-)" \
  -t "${IMAGE_NAME}" \
  "${REPO_DIR}"

echo "==> Building migration image..."
docker build \
  --target builder \
  --build-arg NEXT_PUBLIC_SERVER_URL="$(grep NEXT_PUBLIC_SERVER_URL "${ENV_DIR}/.env" | cut -d= -f2-)" \
  --build-arg NEXT_PUBLIC_SITE_ID="$(grep NEXT_PUBLIC_SITE_ID "${ENV_DIR}/.env" | cut -d= -f2-)" \
  -t "${MIGRATE_IMAGE}" \
  "${REPO_DIR}"

echo "==> Running database migrations..."
docker run --rm \
  --network "${NETWORK_NAME}" \
  --env-file "${ENV_DIR}/.env" \
  "${MIGRATE_IMAGE}" \
  npx payload migrate

echo "==> Stopping old container..."
docker stop "${CONTAINER_NAME}" 2>/dev/null || true
docker rm "${CONTAINER_NAME}" 2>/dev/null || true

echo "==> Starting new container on port ${APP_PORT}..."
docker run -d \
  --name "${CONTAINER_NAME}" \
  --restart unless-stopped \
  --network "${NETWORK_NAME}" \
  --env-file "${ENV_DIR}/.env" \
  -v "uploads-${ENV_NAME}-media:/app/media" \
  -v "uploads-${ENV_NAME}-documents:/app/documents" \
  -p "127.0.0.1:${APP_PORT}:3000" \
  "${IMAGE_NAME}"

echo "==> Fixing volume permissions..."
docker exec -u 0 "${CONTAINER_NAME}" chown -R 1001:1001 /app/media /app/documents

echo "==> Cleaning up old images..."
docker image prune -f

echo "==> Done! ${ENV_NAME} deployed on port ${APP_PORT}"