#!/bin/bash
# Export BMC Office subscriptions from local dev and import to production

set -e

echo "🔍 Eksporterer BMC Office abonnementer fra lokal dev..."

# Export to SQL file with proper escaping
docker exec bmc-hub-postgres psql -U bmc_hub -d bmc_hub -t -A -F',' -c "
SELECT 
  id,
  customer_id,
  firma_id,
  firma_name,
  start_date,
  text,
  antal,
  pris,
  rabat,
  beskrivelse,
  faktura_firma_id,
  faktura_firma_name,
  active
FROM bmc_office_subscriptions
ORDER BY id;" > /tmp/bmc_subs_data.csv

echo "✅ Eksporteret $(wc -l < /tmp/bmc_subs_data.csv) records"

echo ""
echo "📤 Uploader til prod server..."

# Copy file to prod
scp /tmp/bmc_subs_data.csv root@172.16.31.183:/tmp/

echo ""
echo "📥 Importerer på prod server..."

# Import on prod
ssh root@172.16.31.183 << 'ENDSSH'
  echo "🗑️  Rydder eksisterende data..."
  sudo podman exec bmc-hub-postgres-prod psql -U bmchub -d bmchub -c "TRUNCATE TABLE bmc_office_subscriptions RESTART IDENTITY CASCADE;"
  
  echo "📥 Importerer ny data..."
  sudo podman exec -i bmc-hub-postgres-prod psql -U bmchub -d bmchub -c "
    COPY bmc_office_subscriptions (id, customer_id, firma_id, firma_name, start_date, text, antal, pris, rabat, beskrivelse, faktura_firma_id, faktura_firma_name, active)
    FROM '/tmp/bmc_subs_data.csv'
    WITH (FORMAT csv, DELIMITER ',');
  " < /tmp/bmc_subs_data.csv
  
  echo "✅ Import færdig!"
  
  sudo podman exec bmc-hub-postgres-prod psql -U bmchub -d bmchub -c "
    SELECT COUNT(*) as imported_total, 
           ROUND(SUM(total_inkl_moms)::numeric, 2) as total_value 
    FROM bmc_office_subscription_totals 
    WHERE active = true;
  "
ENDSSH

echo ""
echo "🎉 Færdig! BMC Office abonnementer overført til prod."
