#!/bin/sh
set -e

echo "=========================================="
echo "  Dyolink Backend - Docker Entrypoint"
echo "=========================================="

if [ "$NODE_ENV" = "production" ]; then
    echo "Running in PRODUCTION mode"
    echo "Running database migrations..."
    ./node_modules/.bin/prisma migrate deploy
    if [ -f "dist/prisma/seed.js" ]; then
        echo "Seeding reference data (plans, org types, permissions)..."
        node dist/prisma/seed.js
    elif [ -f "prisma/seed.ts" ] || [ -f "prisma/seed.js" ]; then
        echo "Running database seed..."
        ./node_modules/.bin/prisma db seed
    fi
else
    echo "Running in DEVELOPMENT mode"
    echo "Syncing database schema..."
    ./node_modules/.bin/prisma db push
fi

if [ "$NODE_ENV" != "production" ]; then
    if [ -f "prisma/seed.ts" ] || [ -f "prisma/seed.js" ]; then
        echo "Running database seed..."
        ./node_modules/.bin/prisma db seed
    fi
fi

echo "Verifying database connection..."
if ! echo "SELECT 1" | ./node_modules/.bin/prisma db execute --stdin --schema prisma/schema.prisma >/dev/null 2>&1; then
    echo "Cannot connect to database or execute query."
    exit 1
fi
echo "Database connection OK"

echo "Starting Dyolink Backend..."
echo "  Environment: ${NODE_ENV:-development}"
echo "  Port: ${PORT:-3000}"

exec "$@"
