@echo off
setlocal

cd /d "%~dp0"

set "DB_NAME=db_klasifikasi"
set "DB_USER=postgres"

if not "%~1"=="" set "DB_USER=%~1"

echo ================================================
echo Setup Database PostgreSQL
 echo Database : %DB_NAME%
 echo User     : %DB_USER%
echo ================================================

where psql >nul 2>&1
if errorlevel 1 (
  echo [ERROR] psql tidak ditemukan di PATH.
  echo Install PostgreSQL dulu dan pastikan psql bisa dipanggil dari CMD.
  pause
  exit /b 1
)

for /f %%i in ('psql -U %DB_USER% -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname='"'"'%DB_NAME%'"'"'"') do set DB_EXISTS=%%i

if "%DB_EXISTS%"=="1" (
  echo [INFO] Database %DB_NAME% sudah ada.
) else (
  echo [INFO] Membuat database %DB_NAME%...
  psql -U %DB_USER% -d postgres -c "CREATE DATABASE %DB_NAME%;"
  if errorlevel 1 (
    echo [ERROR] Gagal membuat database.
    pause
    exit /b 1
  )
)

echo [INFO] Menjalankan schema: db\schema.sql ...
psql -U %DB_USER% -d %DB_NAME% -f "db\schema.sql"
if errorlevel 1 (
  echo [ERROR] Gagal menjalankan schema SQL.
  pause
  exit /b 1
)

echo.
echo [OK] Database siap.
echo Selanjutnya jalankan aplikasi EXE.
echo.
pause
