@echo off
setlocal enabledelayedexpansion

REM ============================================================
REM  PostgreSQL restore (custom compressed format)
REM  Place this file in the PostgreSQL install dir (next to bin).
REM  Usage:
REM    1) Double-click  -> restores the newest .dump in dumps\
REM    2) Drag a .dump onto this bat -> restores that specific file
REM ============================================================

REM ---------- Connection config (from settings.yaml production) ----------
set "PGHOST=127.0.0.1"
set "PGPORT=8432"
set "PGDATABASE=dcp"
set "PGUSER=postgres"
set "PGPASSWORD=rootroot"

set "PGBIN=%~dp0bin"

REM ---------- Choose backup file ----------
set "INFILE=%~1"
if not defined INFILE (
    set "OUTDIR=%~dp0dumps"
    if not exist "!OUTDIR!" (
        echo No file given and dumps dir not found: !OUTDIR!
        pause
        exit /b 1
    )
    for /f "delims=" %%f in ('dir /b /a-d /o-d "!OUTDIR!\*.dump" 2^>nul') do (
        set "INFILE=!OUTDIR!\%%f"
        goto :gotfile
    )
    echo No .dump file found in !OUTDIR!
    pause
    exit /b 1
)
:gotfile

echo.
echo [RESTORE] target: %PGDATABASE% @ %PGHOST%:%PGPORT%
echo [SOURCE]  %INFILE%
echo           Existing objects will be dropped and recreated. Not reversible.
echo.
choice /c YN /m "Confirm restore (Y/N)"
if errorlevel 2 (
    echo Cancelled.
    pause
    exit /b 0
)

REM --clean --if-exists: drop before create, ignore missing; --no-owner/--no-privileges: adapt target
"%PGBIN%\pg_restore.exe" --clean --if-exists --no-owner --no-privileges -d "%PGDATABASE%" -v "%INFILE%"

if errorlevel 1 (
    echo.
    echo [NOTE] pg_restore returned non-zero. Usually this is just --clean
    echo        "object does not exist / dependency order" warnings.
    echo        Most data is likely restored; review the log above.
) else (
    echo.
    echo [OK] restore finished.
)
pause
