#!/bin/sh
# ──────────────────────────────────────────────────────────────
#  Gembira IMS — Backend container entrypoint
#  1. Siapkan & perbaiki izin folder storage / bootstrap cache
#  2. Tunggu database siap
#  3. Jalankan migrasi (idempoten)
#  4. Seed data awal HANYA pada boot pertama (akun, produk, gudang, channel)
#  5. Start PHP-FPM
# ──────────────────────────────────────────────────────────────
set -e

cd /app

echo "[entrypoint] Menyiapkan direktori storage & cache..."
mkdir -p \
  storage/logs \
  storage/framework/sessions \
  storage/framework/cache \
  storage/framework/views \
  storage/app/public \
  bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache

if [ ! -L public/storage ]; then
  echo "[entrypoint] Membuat symlink public/storage..."
  su-exec www-data php artisan storage:link
fi

DB_PORT="${DB_PORT:-3306}"
echo "[entrypoint] Menunggu database di ${DB_HOST}:${DB_PORT}..."
until php -r '
  $h = getenv("DB_HOST"); $p = getenv("DB_PORT") ?: 3306;
  $u = getenv("DB_USERNAME"); $pw = getenv("DB_PASSWORD");
  try { new PDO("mysql:host=$h;port=$p", $u, $pw); exit(0); }
  catch (Throwable $e) { exit(1); }
' 2>/dev/null; do
  echo "[entrypoint] Database belum siap, coba lagi 3 detik..."
  sleep 3
done
echo "[entrypoint] Koneksi database OK."

echo "[entrypoint] Membersihkan cache lama..."
su-exec www-data php artisan optimize:clear || true

echo "[entrypoint] Menjalankan migrasi database..."
su-exec www-data php artisan migrate --force

if [ ! -f storage/.seeded ]; then
  echo "[entrypoint] Boot pertama terdeteksi — mengisi data awal (seed)..."
  su-exec www-data php artisan db:seed --force || true
  su-exec www-data php artisan db:seed --class=WarehouseSeeder --force || true
  su-exec www-data php artisan db:seed --class=ChannelSeeder --force || true
  su-exec www-data touch storage/.seeded
  echo "[entrypoint] Seeding selesai."
else
  echo "[entrypoint] Penanda seed ditemukan — melewati seeding."
fi

echo "[entrypoint] Menjalankan PHP-FPM..."
# Master php-fpm berjalan sebagai root (agar bisa menulis ke stderr container),
# worker otomatis turun ke www-data sesuai user/group di php-fpm.conf.
exec php-fpm -F
