#!/bin/bash

# Script til at rette forkerte 10-cifrede e-conomic kundenumre
# Baseret på CSV eksport fra e-conomic

set -e

CONTAINER_NAME="bmc-hub-postgres-prod"
DB_USER="bmc_hub"
DB_NAME="bmc_hub"

# Farver til output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${GREEN}🔍 Finder kunder med forkerte 10-cifrede economic_customer_number...${NC}"

# Find alle kunder med 10+ cifrede numre (over 999999999)
echo "SELECT id, name, economic_customer_number FROM customers WHERE economic_customer_number > 999999999 ORDER BY economic_customer_number;" | \
sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME"

echo ""
echo -e "${YELLOW}⚠️  Disse numre er ugyldige i e-conomic (max 9 cifre tilladt)${NC}"
echo ""

# Ret specifikke kendte cases fra CSV
echo -e "${GREEN}🔧 Retter kendte forkerte numre...${NC}"

# PFA kunder med forkerte numre - baseret på mønstre i CSV
# 2065328011 skal være 20653280X (find det rigtige i e-conomic)
# 2065328014 skal være 206532814 eller lignende

# Først: Fjern sidste ciffer hvis det er 1 og nummeret eksisterer i e-conomic
echo -e "${YELLOW}📋 Strategi: Fjerner sidste ciffer fra 10-cifrede numre${NC}"

# Hent alle 10-cifrede numre
INVALID_NUMBERS=$(sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -t -c \
"SELECT id, economic_customer_number FROM customers WHERE economic_customer_number > 999999999;")

if [ -z "$INVALID_NUMBERS" ]; then
    echo -e "${GREEN}✅ Ingen forkerte numre fundet!${NC}"
    exit 0
fi

# For hver forkert nummer, prøv at rette det
echo "$INVALID_NUMBERS" | while IFS='|' read -r id number; do
    id=$(echo "$id" | xargs)
    number=$(echo "$number" | xargs)
    
    if [ -z "$id" ] || [ -z "$number" ]; then
        continue
    fi
    
    # Fjern sidste ciffer
    corrected=$((number / 10))
    
    echo -e "${YELLOW}Kunde ID $id: $number → $corrected${NC}"
    
    # Opdater i database
    sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -c \
    "UPDATE customers SET economic_customer_number = $corrected WHERE id = $id;"
    
    echo -e "${GREEN}✅ Opdateret kunde $id${NC}"
done

echo ""
echo -e "${GREEN}✅ Rettelser komplet!${NC}"
echo ""
echo -e "${YELLOW}📋 Verificer resultatet:${NC}"

sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -c \
"SELECT id, name, economic_customer_number FROM customers WHERE economic_customer_number > 999999999;"

REMAINING=$(sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -t -c \
"SELECT COUNT(*) FROM customers WHERE economic_customer_number > 999999999;")

if [ "$REMAINING" -eq 0 ]; then
    echo -e "${GREEN}✅ Alle kundenumre er nu gyldige!${NC}"
else
    echo -e "${RED}⚠️  $REMAINING kunder har stadig ugyldige numre${NC}"
fi
