#!/bin/sh

echo "Waiting for CockroachDB cluster to be ready..."

# ใช้ Python แทน client cockroach
until python - <<END
import psycopg
import os
try:
    conn = psycopg.connect(
        host=os.environ.get("DB_HOST","cockroach-1"),
        port=os.environ.get("DB_PORT",26257),
        dbname="defaultdb",
        user=os.environ.get("DB_USER","root"),
        password=os.environ.get("DB_PASSWORD","")
    )
    conn.close()
except:
    exit(1)
END
do
  echo "CockroachDB is unavailable - sleeping"
  sleep 1
done

echo "CockroachDB is ready."

# Create DB
python - <<END
import psycopg
import os
conn = psycopg.connect(
    host=os.environ.get("DB_HOST","cockroach-1"),
    port=os.environ.get("DB_PORT",26257),
    dbname="defaultdb",
    user=os.environ.get("DB_USER","root"),
    password=os.environ.get("DB_PASSWORD","")
)
conn.autocommit = True
cur = conn.cursor()
cur.execute(f"CREATE DATABASE IF NOT EXISTS {os.environ.get('DB_NAME','my_db')};")
cur.close()
conn.close()
END

# Migrate & Superuser
python manage.py migrate --noinput
python manage.py shell -c "from django.contrib.auth import get_user_model; User=get_user_model(); User.objects.filter(username='admin').exists() or User.objects.create_superuser('admin','admin@softwarecraft.tech','Str0ngp@ssword123-')"

echo "Starting Django server..."
exec python manage.py runserver 0.0.0.0:8000
