#!/usr/bin/env bash
# Creates this white-label checkout's schema + DB user on ITS OWN MySQL
# container (each branded instance runs its own mysqld — see
# docker-compose.branded.yml's `db` service), then applies
# docker/mysql/init/*.sql to it — skipping the local-dev-only 999_seed.sql
# fixture data — and prints the follow-up step to create that client's one
# real admin login.
#
# Run once, after `docker compose -f docker-compose.branded.yml -p <project>
# up -d` and before the app is used. Reads DB_NAME / DB_USER / DB_PASS /
# MYSQL_ROOT_PASSWORD from this checkout's own root .env — safe to keep at
# rest here, unlike the old shared-server setup, since this is now this
# instance's own independent MySQL credential, not production's. See
# DEPLOY-BRANDED-INSTANCE.md.

set -euo pipefail

PROJECT="${1:?Usage: scripts/init_branded_db.sh <compose-project-name>}"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# shellcheck disable=SC1091
source "$REPO_ROOT/.env"

: "${DB_NAME:?DB_NAME must be set in .env}"
: "${DB_USER:?DB_USER must be set in .env}"
: "${DB_PASS:?DB_PASS must be set in .env}"
: "${MYSQL_ROOT_PASSWORD:?MYSQL_ROOT_PASSWORD must be set in .env}"

COMPOSE=(docker compose -f "$REPO_ROOT/docker-compose.branded.yml" -p "$PROJECT")

echo "Creating schema '$DB_NAME' + user '$DB_USER' on this instance's own MySQL container (project: $PROJECT)..."

"${COMPOSE[@]}" exec -T db mysql -uroot -p"$MYSQL_ROOT_PASSWORD" <<SQL
CREATE DATABASE IF NOT EXISTS \`$DB_NAME\`;
CREATE USER IF NOT EXISTS '$DB_USER'@'%' IDENTIFIED BY '$DB_PASS';
GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'%';
FLUSH PRIVILEGES;
SQL

run_sql() {
    "${COMPOSE[@]}" exec -T db mysql -u"$DB_USER" -p"$DB_PASS" "$DB_NAME"
}

for f in "$REPO_ROOT"/docker/mysql/init/*.sql; do
    name="$(basename "$f")"
    if [ "$name" = "999_seed.sql" ]; then
        echo "Skipping $name (local-dev test fixtures, not for a real client)"
        continue
    fi
    echo "Applying $name"
    run_sql < "$f"
done

echo
echo "Schema applied. Now create this client's one real admin login:"
echo "  1. Hash a real password:"
echo "     docker compose -f docker-compose.branded.yml -p $PROJECT exec app \\"
echo "       php /var/www/html/laravel/artisan tinker --execute=\"echo Hash::make('REPLACE_ME');\""
echo "  2. Insert the admin row with that hash (adjust email/name):"
echo "     docker compose -f docker-compose.branded.yml -p $PROJECT exec -T db \\"
echo "       mysql -u$DB_USER -p$DB_PASS $DB_NAME -e \\"
echo "       \"INSERT INTO users (name, email, password, role, created_at, updated_at)"
echo "        VALUES ('Admin', 'admin@example.com', '<hash from step 1>', 'admin', NOW(), NOW());\""
