#!/usr/bin/env bash
# run-backend.sh - Idempotent script to run the Channel Backend.
# This script starts PostgreSQL, configures env vars, runs database setup/seeding, and boots the backend.

set -e

# Visual formatting helper
info() {
  echo -e "\033[1;34m[INFO]\033[0m $1"
}
error() {
  echo -e "\033[1;31m[ERROR]\033[0m $1"
}

# 1. Verify Docker Installation
if ! command -v docker &> /dev/null; then
  error "Docker is not installed. Please install Docker to spin up PostgreSQL."
  exit 1
fi

# 2. Verify Docker Daemon is running
if ! docker info &> /dev/null; then
  error "Docker daemon is not running. Please start Docker."
  exit 1
fi

# 3. Spin up PostgreSQL & MinIO containers
info "Starting database and storage services via docker-compose..."
docker compose up -d || docker-compose up -d

# 4. Wait for PostgreSQL to be ready inside container
info "Waiting for database to accept connections..."
for i in {1..30}; do
  if docker exec channel_postgres pg_isready -U pipeline_admin -d backend_channel &> /dev/null; then
    info "Database is ready!"
    break
  fi
  if [ $i -eq 30 ]; then
    error "Database ready timeout exceeded."
    exit 1
  fi
  sleep 1
done

# 5. Generate Environment Config
if [ ! -f Channel-Backend/.env ]; then
  info "Generating Channel-Backend/.env config file..."
  cat <<EOT > Channel-Backend/.env
PORT=5000
DATABASE_URL="postgresql://pipeline_admin:secure_pipeline_2024@localhost:5433/backend_channel?schema=public"
JWT_SECRET="super-secret-jwt-key-2026-world-class"
NODE_ENV="development"
MINIO_ENDPOINT="http://localhost:9000"
MINIO_ACCESS_KEY="minio_admin"
MINIO_SECRET_KEY="minio_password_2026"
MINIO_BUCKET="secure-assets"
EOT
else
  info "Channel-Backend/.env file already exists."
fi

# 6. Install Node dependencies
info "Installing backend node packages..."
cd Channel-Backend
npm install

# 7. Generate Prisma Client
info "Generating Prisma client..."
npx prisma generate

# 8. Apply database schema alignments
info "Syncing database schema with Prisma..."
npx prisma db push

# 9. Seed the database (idempotent user / document inserts)
info "Running database seeding..."
npx ts-node seed.ts

info "Running MinIO storage seeding..."
npx ts-node src/seed-minio.ts

# Check if port 5000 is occupied and free it
if lsof -i :5000 &> /dev/null; then
  PORT_PID=$(lsof -t -i :5000)
  info "Port 5000 is occupied by process $PORT_PID. Freeing port..."
  kill -9 $PORT_PID || true
  sleep 1
fi

# 9. Start server
info "Starting Express backend dev server..."
npm run dev
