#!/bin/bash

# Script til at linke tmodule_customers til customers automatisk
# Matcher baseret på navn eller economic_customer_number

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

# Check om container kører
if ! sudo podman ps | grep -q "$CONTAINER_NAME"; then
    echo -e "${RED}❌ Container $CONTAINER_NAME kører ikke!${NC}"
    exit 1
fi

echo -e "${GREEN}🔍 Finder kunder uden hub_customer_id...${NC}"

# Find alle tmodule_customers uden hub_customer_id
UNLINKED=$(sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -t -c "
SELECT COUNT(*) 
FROM tmodule_customers 
WHERE hub_customer_id IS NULL;
")

echo -e "${YELLOW}📊 Fandt $UNLINKED ulinkede kunder${NC}"

if [ "$UNLINKED" -eq 0 ]; then
    echo -e "${GREEN}✅ Alle kunder er allerede linket!${NC}"
    exit 0
fi

echo -e "${GREEN}🔗 Linker kunder baseret på navn match...${NC}"

# Link kunder hvor navnet matcher præcist
LINKED=$(sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -t -c "
UPDATE tmodule_customers tc
SET hub_customer_id = c.id
FROM customers c
WHERE tc.hub_customer_id IS NULL
  AND LOWER(TRIM(tc.name)) = LOWER(TRIM(c.name))
RETURNING tc.id;
" | wc -l)

echo -e "${GREEN}✅ Linkede $LINKED kunder baseret på navn${NC}"

# Link kunder baseret på economic_customer_number (hvis begge har det)
echo -e "${GREEN}🔗 Linker kunder baseret på economic_customer_number...${NC}"

LINKED_ECON=$(sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -t -c "
UPDATE tmodule_customers tc
SET hub_customer_id = c.id
FROM customers c
WHERE tc.hub_customer_id IS NULL
  AND tc.economic_customer_number IS NOT NULL
  AND c.economic_customer_number IS NOT NULL
  AND tc.economic_customer_number = c.economic_customer_number
RETURNING tc.id;
" | wc -l)

echo -e "${GREEN}✅ Linkede $LINKED_ECON kunder baseret på economic_customer_number${NC}"

# Vis stadig ulinkede kunder
echo -e "${YELLOW}📋 Kunder der stadig mangler link:${NC}"

sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -c "
SELECT 
    tc.id,
    tc.vtiger_id,
    tc.name,
    tc.economic_customer_number
FROM tmodule_customers tc
WHERE tc.hub_customer_id IS NULL
ORDER BY tc.name
LIMIT 20;
"

REMAINING=$(sudo podman exec -i "$CONTAINER_NAME" psql -U "$DB_USER" -d "$DB_NAME" -t -c "
SELECT COUNT(*) 
FROM tmodule_customers 
WHERE hub_customer_id IS NULL;
")

echo -e "${YELLOW}⚠️  $REMAINING kunder mangler stadig link${NC}"

if [ "$REMAINING" -gt 0 ]; then
    echo -e "${YELLOW}💡 Disse skal linkes manuelt via UI eller direkte SQL${NC}"
fi

echo -e "${GREEN}✅ Linking komplet!${NC}"
