#!/usr/bin/env bash
# Initialise one or both SQLite databases from schema.sql.
# Safe to run on existing databases — schema uses IF NOT EXISTS / INSERT OR IGNORE.
# Usage:
#   scripts/migrate.sh              # both test.db and posterg.db
#   scripts/migrate.sh test         # storage/test.db only
#   scripts/migrate.sh prod         # storage/posterg.db only

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
APP_DIR="$REPO_ROOT/app"
SCHEMA="$APP_DIR/storage/schema.sql"
TEST_DB="$APP_DIR/storage/test.db"
PROD_DB="$APP_DIR/storage/posterg.db"

init_db() {
    local db="$1"
    local label="$2"
    echo "  [$label] applying schema…"
    sqlite3 "$db" < "$SCHEMA"
    echo "  [$label] done"
}

TARGET="${1:-both}"

case "$TARGET" in
    test)  init_db "$TEST_DB"  "test.db"    ;;
    prod)  init_db "$PROD_DB"  "posterg.db" ;;
    both)
        init_db "$TEST_DB"  "test.db"
        init_db "$PROD_DB"  "posterg.db"
        ;;
    *)
        echo "Usage: $0 [test|prod|both]" >&2
        exit 1
        ;;
esac
