#!/bin/bash

# Simpel version - ingen fancy features
CSV_FILE="$1"
CONTAINER="bmc-hub-postgres-prod"

if [ -z "$CSV_FILE" ]; then
    echo "Brug: $0 <csv-file>"
    exit 1
fi

echo "Reading $CSV_FILE..."
LINE_NO=0
UPDATED=0

while IFS=';' read -r nummer navn rest; do
    LINE_NO=$((LINE_NO + 1))
    
    # Skip første 4 linjer
    if [ $LINE_NO -le 4 ]; then
        continue
    fi
    
    # Clean nummer og navn
    nummer=$(echo "$nummer" | tr -cd '0-9')
    navn=$(echo "$navn" | xargs)
    
    # Skip hvis tomt
    if [ -z "$nummer" ] || [ -z "$navn" ]; then
        continue
    fi
    
    echo "[$LINE_NO] $nummer - $navn"
    
    # Escape quotes
    navn_esc=$(echo "$navn" | sed "s/'/''/g")
    
    # Find kunde
    ID=$(sudo podman exec -i "$CONTAINER" psql -U bmc_hub -d bmc_hub -t -c \
        "SELECT id FROM customers WHERE LOWER(name) = LOWER('$navn_esc') LIMIT 1;" | xargs)
    
    if [ -n "$ID" ]; then
        # Update
        sudo podman exec -i "$CONTAINER" psql -U bmc_hub -d bmc_hub -c \
            "UPDATE customers SET economic_customer_number = $nummer WHERE id = $ID;" > /dev/null
        echo "  ✅ Updated ID $ID"
        UPDATED=$((UPDATED + 1))
    else
        # Create
        sudo podman exec -i "$CONTAINER" psql -U bmc_hub -d bmc_hub -c \
            "INSERT INTO customers (name, economic_customer_number, created_at, updated_at) VALUES ('$navn_esc', $nummer, NOW(), NOW());" > /dev/null
        echo "  ➕ Created"
        UPDATED=$((UPDATED + 1))
    fi
done < "$CSV_FILE"

echo ""
echo "Done! Updated: $UPDATED customers"
