#!/bin/sh
set -e

# Baskit Ops container entrypoint.

# --- Materialise .env from the injected environment -------------------------
# Apache/mod_php does not reliably expose env vars whose names contain dots
# (e.g. app.baseURL, database.default.*) to PHP's getenv() at request time, so
# CI4 silently falls back to the Config defaults (localhost:8080, empty DB pass).
# CI4 *does* read a .env file directly, so we write one here — mapping plain,
# shell-safe variables (passed by the compose file) to CI4's dotted keys.
ENV_FILE=/var/www/html/.env
{
    echo "CI_ENVIRONMENT=${CI_ENVIRONMENT:-production}"
    [ -n "$APP_BASEURL" ]         && echo "app.baseURL=${APP_BASEURL}"
    [ -n "$DB_HOST" ]             && echo "database.default.hostname=${DB_HOST}"
    [ -n "$DB_NAME" ]             && echo "database.default.database=${DB_NAME}"
    [ -n "$DB_USER" ]             && echo "database.default.username=${DB_USER}"
    [ -n "$DB_PASS" ]             && echo "database.default.password=${DB_PASS}"
    echo "database.default.DBDriver=${DB_DRIVER:-Postgre}"
    echo "database.default.port=${DB_PORT:-5432}"
    [ -n "$ENCRYPTION_KEY" ]      && echo "encryption.key=${ENCRYPTION_KEY}"
    [ -n "$INGEST_SERVICE_KEY" ]  && echo "INGEST_SERVICE_KEY=${INGEST_SERVICE_KEY}"
    [ -n "$INGEST_ALLOWED_IPS" ]  && echo "INGEST_ALLOWED_IPS=${INGEST_ALLOWED_IPS}"
    [ -n "$JWT_SECRET" ]          && echo "JWT_SECRET=${JWT_SECRET}"
    [ -n "$JWT_ACCESS_TTL" ]      && echo "JWT_ACCESS_TTL=${JWT_ACCESS_TTL}"
    [ -n "$JWT_REFRESH_TTL" ]     && echo "JWT_REFRESH_TTL=${JWT_REFRESH_TTL}"
    if [ -n "$SMTP_HOST" ]; then
        echo "email.protocol=${EMAIL_PROTOCOL:-smtp}"
        echo "email.SMTPHost=${SMTP_HOST}"
        echo "email.SMTPUser=${SMTP_USER:-}"
        echo "email.SMTPPass=${SMTP_PASS:-}"
        echo "email.SMTPPort=${SMTP_PORT:-587}"
        echo "email.SMTPTimeout=${SMTP_TIMEOUT:-10}"
        echo "email.SMTPCrypto=${SMTP_CRYPTO:-tls}"
        echo "email.fromEmail=${EMAIL_FROM:-no-reply@baskit.co.za}"
        echo "email.fromName=\"${EMAIL_FROM_NAME:-Baskit Ops}\""
    fi
    [ -n "$PIPELINE_ALERT_EMAIL" ] && echo "PIPELINE_ALERT_EMAIL=${PIPELINE_ALERT_EMAIL}"
    echo "PIPELINE_ALERT_EMAIL_ENABLED=${PIPELINE_ALERT_EMAIL_ENABLED:-true}"
    [ -n "$PIPELINE_ALERT_WEBHOOK_URL" ] && echo "PIPELINE_ALERT_WEBHOOK_URL=${PIPELINE_ALERT_WEBHOOK_URL}"
} > "$ENV_FILE"
chown www-data:www-data "$ENV_FILE" 2>/dev/null || true

# Migrations are gated behind RUN_MIGRATIONS so that in multi-replica
# production the schema is migrated once by the deploy pipeline, not by
# every booting replica. For local/dev it defaults to running them.
: "${RUN_MIGRATIONS:=true}"

if [ "$RUN_MIGRATIONS" = "true" ]; then
    echo "[entrypoint] Running database migrations..."
    php spark migrate --all || {
        echo "[entrypoint] Migration failed" >&2
        exit 1
    }
fi

# Ensure the initial console owner exists (idempotent; no-ops if unset/present).
if [ -n "$ADMIN_EMAIL" ] && [ -n "$ADMIN_PASSWORD" ]; then
    echo "[entrypoint] Ensuring admin user..."
    php spark db:seed AdminUserSeeder || echo "[entrypoint] admin seed failed (continuing)" >&2
fi

# Optional demo/reference seeders for fresh environments (idempotent).
if [ "$RUN_SEEDERS" = "true" ]; then
    echo "[entrypoint] Running reference seeders..."
    php spark db:seed RetailerSeeder || echo "[entrypoint] RetailerSeeder failed (continuing)" >&2
    php spark db:seed CatalogSeeder || echo "[entrypoint] CatalogSeeder failed (continuing)" >&2
fi

# Optional: seed live retailer-special placements from catalogue API (idempotent).
if [ "${ADS_SEED_SPECIALS:-false}" = "true" ]; then
    echo "[entrypoint] Seeding retailer ad placements..."
    php spark ads:seed-specials --force || echo "[entrypoint] ads:seed-specials failed (continuing)" >&2
fi

# Optional: map all live products to canonical categories (idempotent).
if [ "${CATALOG_MAP_PRODUCTS:-false}" = "true" ]; then
    echo "[entrypoint] Mapping products to canonical categories..."
    php spark catalog:map-products || echo "[entrypoint] catalog:map-products failed (continuing)" >&2
fi

# Warm the config cache is not needed; hand off to the CMD (apache2-foreground)
exec "$@"
