#!/usr/bin/env bash
set -euo pipefail

DB_NAME="freshyo-dev"
DUMP_DIR="./dumps"
MIGRATION_FILE="./migrated.sql"

if ! command -v wrangler >/dev/null 2>&1; then
  echo "wrangler not found in PATH"
  exit 1
fi

if [ ! -f "$MIGRATION_FILE" ]; then
  echo "Migration file not found: $MIGRATION_FILE"
  exit 1
fi

mkdir -p "$DUMP_DIR"

TIMESTAMP="$(date +"%d%m%y_%H%M")"
DUMP_FILE="${DUMP_DIR}/${TIMESTAMP}_${DB_NAME}.sql"

wrangler d1 export "$DB_NAME" --remote --output "$DUMP_FILE"
wrangler d1 delete "$DB_NAME"
wrangler d1 create "$DB_NAME"
wrangler d1 execute "$DB_NAME" --remote --file="$MIGRATION_FILE"

echo "Done. Dump saved at: $DUMP_FILE"
