#!/usr/bin/env bash
set -euo pipefail

# scripts/create_superuser.sh
# Usage: ./scripts/create_superuser.sh
# This script reads ADMIN_USERNAME, ADMIN_EMAIL, ADMIN_PASSWORD from .env (or environment)
# and creates the superuser inside the Django web container.

BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
if [[ -f "$BASE_DIR/.env" ]]; then
  export $(grep -v '^#' $BASE_DIR/.env | xargs)
fi

: ${ADMIN_USERNAME:="admin"}
: ${ADMIN_EMAIL:="admin@example.com"}
: ${ADMIN_PASSWORD:="changeme"}

echo "Creating superuser: $ADMIN_USERNAME"

docker-compose exec -T web python manage.py shell <<PY
from django.contrib.auth import get_user_model
User = get_user_model()
username = '${ADMIN_USERNAME}'
email = '${ADMIN_EMAIL}'
password = '${ADMIN_PASSWORD}'
if not User.objects.filter(username=username).exists():
    User.objects.create_superuser(username=username, email=email, password=password)
    print('Superuser created')
else:
    u = User.objects.filter(username=username).first()
    u.email = email
    u.is_superuser = True
    u.is_staff = True
    u.set_password(password)
    u.save()
    print('Superuser updated')
PY

echo "Done. You can log in at http://localhost:8000/admin with the credentials above (if backend is running)."
