#!/bin/sh
echo "Starting Xpeditis Backend..."
echo "Waiting for PostgreSQL..."
max_attempts=30
attempt=0
while [ $attempt -lt $max_attempts ]; do
  if node -e "const { Client } = require('pg'); const client = new Client({ host: process.env.DATABASE_HOST, port: process.env.DATABASE_PORT, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME }); client.connect().then(() => { client.end(); process.exit(0); }).catch(() => process.exit(1));" 2>/dev/null; then
    echo "PostgreSQL is ready"
    break
  fi
  attempt=$((attempt + 1))
  echo "Attempt $attempt/$max_attempts - Retrying..."
  sleep 2
done
if [ $attempt -eq $max_attempts ]; then
  echo "Failed to connect to PostgreSQL"
  exit 1
fi
echo "Running database migrations..."
node /app/run-migrations.js
if [ $? -ne 0 ]; then
  echo "Migrations failed"
  exit 1
fi
echo "Starting NestJS application..."
exec "$@"
