#!/bin/bash
set -e

REMOTE_DB_HOST="db.cpaksmmlpaxeqdtztfor.supabase.co"
REMOTE_DB_USER="postgres"
REMOTE_DB_NAME="postgres"
REMOTE_DB_PASS="ku1soi2SMvRWCKIs"
LOCAL_CONTAINER="supabase-db"
LOCAL_DB_USER="supabase_admin"
LOCAL_DB_NAME="postgres"

YELLOW="\033[1;33m"
GREEN="\033[1;32m"
BLUE="\033[1;34m"
RED="\033[1;31m"
RESET="\033[0m"

while [[ "$#" -gt 0 ]]; do
  case $1 in
    --table) TABLE="$2"; shift ;;
    *) echo -e "${RED}Unknown parameter:${RESET} $1"; exit 1 ;;
  esac
  shift
done

if [ -z "$TABLE" ]; then
  echo -e "${YELLOW}Usage:${RESET} $0 --table <table_name>"
  exit 1
fi

echo -e "${BLUE}→ Preparing local table for fast import...${RESET}"
docker exec -i $LOCAL_CONTAINER psql -U $LOCAL_DB_USER -d $LOCAL_DB_NAME <<SQL
SET session_replication_role = replica;
ALTER TABLE IF EXISTS $TABLE DISABLE TRIGGER ALL;
TRUNCATE TABLE $TABLE;
SQL

echo -e "${BLUE}→ Bulk dumping and importing:${RESET} ${YELLOW}$TABLE${RESET}"
PGPASSWORD="$REMOTE_DB_PASS" pg_dump -h $REMOTE_DB_HOST -U $REMOTE_DB_USER -d $REMOTE_DB_NAME \
  -t $TABLE --data-only --inserts --disable-triggers --no-owner --no-comments \
  | sed -E "s/public\.${TABLE}_id_seq1/public.${TABLE}_id_seq/g" \
  | docker exec -i $LOCAL_CONTAINER psql -U $LOCAL_DB_USER -d $LOCAL_DB_NAME

echo -e "${BLUE}→ Restoring triggers and constraints...${RESET}"
docker exec -i $LOCAL_CONTAINER psql -U $LOCAL_DB_USER -d $LOCAL_DB_NAME <<SQL
SET session_replication_role = origin;
ALTER TABLE IF EXISTS $TABLE ENABLE TRIGGER ALL;
SQL

echo -e "${GREEN}✅ Imported table:${RESET} ${YELLOW}$TABLE${RESET}"
