#!/usr/bin/env bash
# Import SQL dump into drafts.db, replacing existing data.
# Usage: scripts/db-import.sh [input_path]

set -euo pipefail

DB="data/drafts.db"
IN="${1:-data/drafts.sql.gz}"

if [[ ! -f "$IN" ]]; then
    echo "Error: $IN not found" >&2
    exit 1
fi

if [[ -f "$DB" ]]; then
    BACKUP="data/drafts.db.bak.$(date +%s)"
    echo "Backing up existing DB → $BACKUP"
    cp "$DB" "$BACKUP"
    rm "$DB"
fi

echo "Importing $IN → $DB"
gunzip -c "$IN" | sqlite3 "$DB"

ROWS=$(sqlite3 "$DB" "SELECT count(*) FROM drafts;")
echo "Done: $ROWS drafts restored"
