All files / config database.js

0.41% Statements 7/1691
0.13% Branches 1/719
0% Functions 0/57
0.44% Lines 7/1574

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705              1x 1x 1x 1x     1x                           1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1x          
/**
 * Database Configuration and Initialization
 * Multi-tenant database setup with comprehensive schema
 * 
 * @module config/database
 */
 
const mysql = require('mysql2/promise');
const { logger } = require('./logger');
const bcrypt = require('bcryptjs');
require('dotenv').config();
 
// Database configuration
const dbConfig = {
  host: process.env.DB_HOST,
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 20,
  queueLimit: 0,
  enableKeepAlive: true,
  keepAliveInitialDelay: 0
};
 
// Create connection pool
const pool = mysql.createPool(dbConfig);
 
// Note: max_allowed_packet should be configured in MySQL server configuration (my.ini/my.cnf)
// Add this line to [mysqld] section: max_allowed_packet=64M
// The default value (usually 16MB-64MB) should be sufficient for most email templates
 
/**
 * Test database connection
 */
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    logger.info('✅ Database connection successful');
    connection.release();
    return true;
  } catch (error) {
    logger.error('❌ Database connection failed', { error: error.message });
    throw error;
  }
}
 
/**
 * Initialize database schema
 */
async function initDatabase() {
  let connection;
  try {
    connection = await pool.getConnection();
    logger.info('📄 Initializing database schema...');
 
    // Wrap all operations in try-catch to identify exact error location
    try {
 
    // Create super_admins table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS super_admins (
        id INT AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(255) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        name VARCHAR(100) NOT NULL,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_email (email),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ super_admins table created/verified');
 
    // Create tenants table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tenants (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        subdomain VARCHAR(50) UNIQUE NOT NULL,
        email VARCHAR(255) NOT NULL,
        phone VARCHAR(20),
        company_name VARCHAR(150),
        plan_id INT,
        status ENUM('active', 'suspended', 'cancelled', 'trial', 'grace_period', 'pending') DEFAULT 'trial',
        trial_ends_at TIMESTAMP NULL,
        subscription_id VARCHAR(255),
        stripe_customer_id VARCHAR(255),
        paypal_subscription_id VARCHAR(255),
        pagbank_customer_id VARCHAR(255),
        max_users INT DEFAULT 5,
        max_stores INT DEFAULT 1,
        max_departments INT DEFAULT 5,
        max_contacts INT DEFAULT 1000,
        max_devices INT DEFAULT 1,
        max_conversations INT DEFAULT 1000,
        max_messages_per_month INT DEFAULT 10000,
        max_faqs INT DEFAULT 10,
        max_widgets INT DEFAULT 1,
        max_invoices_per_month INT DEFAULT 50,
        max_quotes_per_month INT DEFAULT 50,
        max_payment_links_per_month INT DEFAULT 50,
        max_email_accounts INT DEFAULT 0,
        max_emails_per_month INT DEFAULT 0,
        max_omnichannel_accounts INT DEFAULT 0,
        max_contact_groups INT DEFAULT 10,
        bot_enabled BOOLEAN DEFAULT TRUE,
        group_enabled BOOLEAN DEFAULT FALSE,
        current_messages_count INT DEFAULT 0,
        messages_reset_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        subscription_start_date TIMESTAMP NULL,
        subscription_end_date TIMESTAMP NULL,
        grace_period_end TIMESTAMP NULL,
        next_billing_date TIMESTAMP NULL,
        last_payment_date TIMESTAMP NULL,
        payment_status ENUM('paid', 'pending', 'overdue', 'failed') DEFAULT 'pending',
        suspension_date TIMESTAMP NULL,
        preferred_language VARCHAR(5) DEFAULT 'en',
        settings JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_subdomain (subdomain),
        INDEX idx_email (email),
        INDEX idx_status (status),
        INDEX idx_plan (plan_id),
        INDEX idx_payment_status (payment_status),
        INDEX idx_next_billing_date (next_billing_date),
        INDEX idx_grace_period_end (grace_period_end)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tenants table created/verified');
 
    // Add bot_enabled and group_enabled columns if they don't exist (for existing databases)
    try {
      await connection.execute(`
        ALTER TABLE tenants 
        ADD COLUMN IF NOT EXISTS bot_enabled BOOLEAN DEFAULT TRUE,
        ADD COLUMN IF NOT EXISTS group_enabled BOOLEAN DEFAULT FALSE
      `);
      logger.info('✅ bot_enabled and group_enabled columns added/verified');
    } catch (alterError) {
      // MySQL doesn't support IF NOT EXISTS for columns, try individual adds
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN bot_enabled BOOLEAN DEFAULT TRUE`);
      } catch (e) { /* Column might already exist */ }
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN group_enabled BOOLEAN DEFAULT FALSE`);
      } catch (e) { /* Column might already exist */ }
      logger.info('✅ bot_enabled and group_enabled columns checked');
    }
 
    try {
      await connection.execute(`
        ALTER TABLE tenants 
        ADD COLUMN IF NOT EXISTS max_email_accounts INT DEFAULT 0,
        ADD COLUMN IF NOT EXISTS max_emails_per_month INT DEFAULT 0,
        ADD COLUMN IF NOT EXISTS max_omnichannel_accounts INT DEFAULT 0,
        ADD COLUMN IF NOT EXISTS max_whatsapp_cloud_accounts INT DEFAULT 1
      `);
      logger.info('✅ max_email_accounts, max_emails_per_month, max_omnichannel_accounts and max_whatsapp_cloud_accounts columns added/verified');
    } catch (alterError) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_email_accounts INT DEFAULT 0`);
      } catch (e) { }
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_emails_per_month INT DEFAULT 0`);
      } catch (e) { }
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_omnichannel_accounts INT DEFAULT 0`);
      } catch (e) { }
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_whatsapp_cloud_accounts INT DEFAULT 1`);
      } catch (e) { }
      logger.info('✅ max_email_accounts, max_emails_per_month, max_omnichannel_accounts and max_whatsapp_cloud_accounts columns checked');
    }
 
    // Add billing_period column to tenants table
    try {
      await connection.execute(`ALTER TABLE tenants ADD COLUMN billing_period ENUM('monthly', 'yearly') DEFAULT 'monthly' AFTER plan_id`);
      logger.info('✅ Added billing_period column to tenants table');
    } catch (e) {
      if (e.code !== 'ER_DUP_FIELDNAME') {
        logger.warn('billing_period column:', e.message);
      }
    }
 
    // Create subscription_plans table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS subscription_plans (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        description TEXT,
        price DECIMAL(10,2) NOT NULL,
        currency VARCHAR(3) DEFAULT 'USD',
        billing_period ENUM('monthly', 'yearly') DEFAULT 'monthly',
        max_stores INT DEFAULT 1,
        max_users INT DEFAULT 5,
        max_departments INT DEFAULT 5,
        max_contacts INT DEFAULT 1000,
        max_devices INT DEFAULT 1,
        max_conversations INT DEFAULT 1000,
        max_messages_per_month INT DEFAULT 10000,
        max_contact_groups INT DEFAULT 10,
        max_faqs INT DEFAULT 10,
        max_widgets INT DEFAULT 1,
        max_invoices_per_month INT DEFAULT 50,
        max_quotes_per_month INT DEFAULT 50,
        max_payment_links_per_month INT DEFAULT 50,
        max_email_accounts INT DEFAULT 0,
        max_emails_per_month INT DEFAULT 0,
        max_omnichannel_accounts INT DEFAULT 0,
        whatsapp_enabled BOOLEAN DEFAULT TRUE,
        ai_enabled BOOLEAN DEFAULT FALSE,
        woocommerce_enabled BOOLEAN DEFAULT FALSE,
        analytics_enabled BOOLEAN DEFAULT TRUE,
        priority_support_enabled BOOLEAN DEFAULT FALSE,
        api_access_enabled BOOLEAN DEFAULT FALSE,
        custom_branding_enabled BOOLEAN DEFAULT FALSE,
        invoices_enabled BOOLEAN DEFAULT FALSE,
        quotes_enabled BOOLEAN DEFAULT FALSE,
        widgets_enabled BOOLEAN DEFAULT FALSE,
        payment_links_enabled BOOLEAN DEFAULT FALSE,
        biolink_enabled BOOLEAN DEFAULT FALSE,
        max_bio_pages INT DEFAULT 0,
        max_short_links INT DEFAULT 0,
        max_file_transfers INT DEFAULT 0,
        max_vcards INT DEFAULT 0,
        max_event_links INT DEFAULT 0,
        max_html_pages INT DEFAULT 0,
        max_qr_codes INT DEFAULT 0,
        is_trial BOOLEAN DEFAULT FALSE,
        trial_days INT DEFAULT 0,
        is_free BOOLEAN DEFAULT FALSE,
        features JSON,
        stripe_price_id VARCHAR(255),
        paypal_plan_id VARCHAR(255),
        pagbank_plan_id VARCHAR(255),
        active BOOLEAN DEFAULT TRUE,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_active (active),
        INDEX idx_sort (sort_order),
        INDEX idx_is_trial (is_trial),
        INDEX idx_is_free (is_free)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ subscription_plans table created/verified');
 
    try {
      await connection.execute(`
        ALTER TABLE subscription_plans 
        ADD COLUMN IF NOT EXISTS max_email_accounts INT DEFAULT 0,
        ADD COLUMN IF NOT EXISTS max_emails_per_month INT DEFAULT 0,
        ADD COLUMN IF NOT EXISTS max_omnichannel_accounts INT DEFAULT 0,
        ADD COLUMN IF NOT EXISTS max_whatsapp_cloud_accounts INT DEFAULT 1,
        ADD COLUMN IF NOT EXISTS mass_send_enabled BOOLEAN DEFAULT TRUE
      `);
      logger.info('✅ subscription_plans email, omnichannel, whatsapp cloud and mass_send columns added/verified');
    } catch (alterError) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_email_accounts INT DEFAULT 0`);
      } catch (e) { }
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_emails_per_month INT DEFAULT 0`);
      } catch (e) { }
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_omnichannel_accounts INT DEFAULT 0`);
      } catch (e) { }
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_whatsapp_cloud_accounts INT DEFAULT 1`);
      } catch (e) { }
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN mass_send_enabled BOOLEAN DEFAULT TRUE`);
      } catch (e) { }
      logger.info('✅ subscription_plans email, omnichannel, whatsapp cloud and mass_send columns checked');
    }
 
    // Create currencies table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS currencies (
        id INT AUTO_INCREMENT PRIMARY KEY,
        code VARCHAR(3) UNIQUE NOT NULL,
        name VARCHAR(50) NOT NULL,
        symbol VARCHAR(10) NOT NULL,
        exchange_rate DECIMAL(10,4) DEFAULT 1.0000,
        active BOOLEAN DEFAULT TRUE,
        is_default BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_code (code),
        INDEX idx_active (active),
        INDEX idx_default (is_default)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ currencies table created/verified');
 
    // Create translations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS translations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        language_code VARCHAR(5) NOT NULL,
        language_name VARCHAR(50) NOT NULL,
        translation_key VARCHAR(255) NOT NULL,
        translation_value TEXT NOT NULL,
        category VARCHAR(50) DEFAULT 'general',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_translation (language_code, translation_key),
        INDEX idx_language (language_code),
        INDEX idx_key (translation_key),
        INDEX idx_category (category)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ translations table created/verified');
 
    // Create admins table (tenant admins)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS admins (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        username VARCHAR(50) NOT NULL,
        email VARCHAR(255) NOT NULL,
        password VARCHAR(255) NOT NULL,
        name VARCHAR(100),
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_username (tenant_id, username),
        UNIQUE KEY unique_tenant_email (tenant_id, email),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_username (username),
        INDEX idx_email (email)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ admins table created/verified');
 
    // Add password reset columns to admins table if they don't exist
    const [adminColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'admins'
    `);
    const existingAdminColumns = adminColumns.map(col => col.COLUMN_NAME);
 
    if (!existingAdminColumns.includes('password_reset_token')) {
      try {
        await connection.execute(`
          ALTER TABLE admins 
          ADD COLUMN password_reset_token VARCHAR(255) NULL AFTER password,
          ADD COLUMN password_reset_expires TIMESTAMP NULL AFTER password_reset_token
        `);
        logger.info('✅ Added password reset columns to admins table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('password_reset columns:', e.message);
        }
      }
    }
 
    // Add password reset columns to users table if they don't exist
    const [userColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'users'
    `);
    const existingUserColumns = userColumns.map(col => col.COLUMN_NAME);
 
    if (!existingUserColumns.includes('password_reset_token')) {
      try {
        await connection.execute(`
          ALTER TABLE users 
          ADD COLUMN password_reset_token VARCHAR(255) NULL AFTER password,
          ADD COLUMN password_reset_expires TIMESTAMP NULL AFTER password_reset_token
        `);
        logger.info('✅ Added password reset columns to users table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('users password_reset columns:', e.message);
        }
      }
    }
 
    // Create users table (tenant employees)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL DEFAULT 1,
        username VARCHAR(50) NOT NULL,
        email VARCHAR(255),
        password VARCHAR(255) NOT NULL,
        password_reset_token VARCHAR(255) NULL,
        password_reset_expires TIMESTAMP NULL,
        name VARCHAR(100),
        role ENUM('admin', 'user') DEFAULT 'user',
        store VARCHAR(100),
        department VARCHAR(100),
        store_id INT NULL,
        department_id INT NULL,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_username (tenant_id, username),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_username (username),
        INDEX idx_role (role),
        INDEX idx_store (store),
        INDEX idx_department (department),
        INDEX idx_store_id (store_id),
        INDEX idx_department_id (department_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ users table created/verified');
 
    // Add foreign keys for store_id and department_id after stores and departments tables are created
    // This will be done after those tables are created
 
    // Create stores table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS stores (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(100) NOT NULL,
        description TEXT,
        address VARCHAR(255),
        phone VARCHAR(20),
        email VARCHAR(100),
        hours TEXT,
        promotions TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_store (tenant_id, name),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_name (name)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ stores table created/verified');
 
    // Create departments table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS departments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(100) NOT NULL,
        description TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_department (tenant_id, name),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_name (name)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ departments table created/verified');
 
    // Add is_active column to stores and departments
    try {
      await connection.execute(`ALTER TABLE stores ADD COLUMN IF NOT EXISTS is_active BOOLEAN DEFAULT TRUE AFTER email`);
      logger.info('✅ Added is_active column to stores table');
    } catch (e) { /* Ignore if already exists */ }
 
    try {
      await connection.execute(`ALTER TABLE departments ADD COLUMN IF NOT EXISTS is_active BOOLEAN DEFAULT TRUE AFTER description`);
      logger.info('✅ Added is_active column to departments table');
    } catch (e) { /* Ignore if already exists */ }
 
    // Add foreign keys for store_id and department_id in users table
    // These are added after stores and departments tables exist
    try {
      await connection.execute(`
        ALTER TABLE users 
        ADD CONSTRAINT fk_users_store FOREIGN KEY (store_id) REFERENCES stores(id) ON DELETE SET NULL
      `);
      logger.info('✅ Added store_id foreign key to users table');
    } catch (e) {
      if (e.code !== 'ER_DUP_KEYNAME' && e.code !== 'ER_FK_DUP_NAME') {
        logger.warn('store_id FK:', e.message);
      }
    }
 
    try {
      await connection.execute(`
        ALTER TABLE users 
        ADD CONSTRAINT fk_users_department FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL
      `);
      logger.info('✅ Added department_id foreign key to users table');
    } catch (e) {
      if (e.code !== 'ER_DUP_KEYNAME' && e.code !== 'ER_FK_DUP_NAME') {
        logger.warn('department_id FK:', e.message);
      }
    }
 
    // Create conversations table (without contact_id FK - will be added later)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS conversations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        contact_id INT,
        phone_number VARCHAR(20) NOT NULL,
        remote_jid VARCHAR(255),
        contact_name VARCHAR(100),
        last_message TEXT,
        last_message_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        status ENUM('waiting', 'attended', 'closed', 'active', 'archived') DEFAULT 'waiting',
        assigned_user_id INT,
        assigned_store VARCHAR(100),
        assigned_department VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (assigned_user_id) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_contact (contact_id),
        INDEX idx_phone (phone_number),
        INDEX idx_remote_jid (remote_jid),
        INDEX idx_status (status),
        INDEX idx_last_message_time (last_message_time),
        UNIQUE KEY idx_tenant_remote_jid (tenant_id, remote_jid)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ conversations table created/verified');
 
    // Add missing columns to conversations table if they don't exist
    const [conversationColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'conversations'
    `);
    
    const existingColumns = conversationColumns.map(col => col.COLUMN_NAME);
    
    if (!existingColumns.includes('contact_id')) {
      await connection.execute(`
        ALTER TABLE conversations 
        ADD COLUMN contact_id INT NULL AFTER tenant_id,
        ADD CONSTRAINT fk_conversations_contact FOREIGN KEY (contact_id) REFERENCES contacts(id) ON DELETE SET NULL
      `);
      logger.info('✅ Added contact_id column to conversations table');
    }
    
    if (!existingColumns.includes('updated_at')) {
      await connection.execute(`
        ALTER TABLE conversations 
        ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      `);
      logger.info('✅ Added updated_at column to conversations table');
    }
    
    if (!existingColumns.includes('remote_jid')) {
      await connection.execute(`
        ALTER TABLE conversations 
        ADD COLUMN remote_jid VARCHAR(255) AFTER phone_number
      `);
      logger.info('✅ Added remote_jid column to conversations table');
      
      // Populate remote_jid from phone_number for existing records
      await connection.execute(`
        UPDATE conversations 
        SET remote_jid = CONCAT(phone_number, '@lid')
        WHERE remote_jid IS NULL OR remote_jid = ''
      `);
      logger.info('✅ Populated remote_jid from phone_number');
      
      // Add index for remote_jid
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_remote_jid ON conversations(remote_jid)
      `);
      logger.info('✅ Added index for remote_jid');
      
      // Add unique constraint for tenant_id + remote_jid
      try {
        await connection.execute(`
          CREATE UNIQUE INDEX idx_tenant_remote_jid ON conversations(tenant_id, remote_jid)
        `);
        logger.info('✅ Added unique constraint for tenant_id + remote_jid');
      } catch (err) {
        // Index might already exist or there are duplicates
        logger.warn('Could not create unique index on tenant_id + remote_jid', { error: err.message });
      }
    }
 
    // Add claimed_by_user_id column for exclusive conversation attendance
    if (!existingColumns.includes('claimed_by_user_id')) {
      try {
        await connection.execute(`
          ALTER TABLE conversations 
          ADD COLUMN claimed_by_user_id INT NULL AFTER assigned_user_id,
          ADD COLUMN claimed_at TIMESTAMP NULL AFTER claimed_by_user_id,
          ADD COLUMN is_claimed BOOLEAN DEFAULT FALSE AFTER claimed_at
        `);
        logger.info('✅ Added claimed_by_user_id, claimed_at, is_claimed columns to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('claimed columns:', e.message); }
    }
 
    // Add claimed_at column if not exists
    if (!existingColumns.includes('claimed_at')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN claimed_at TIMESTAMP NULL AFTER claimed_by_user_id`);
        logger.info('✅ Added claimed_at column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('claimed_at:', e.message); }
    }
 
    // Add is_claimed column if not exists
    if (!existingColumns.includes('is_claimed')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN is_claimed BOOLEAN DEFAULT FALSE AFTER claimed_at`);
        logger.info('✅ Added is_claimed column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('is_claimed:', e.message); }
    }
 
    // Add transferred_to_store column for conversation transfer
    if (!existingColumns.includes('transferred_to_store')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN transferred_to_store VARCHAR(100) NULL AFTER is_claimed`);
        logger.info('✅ Added transferred_to_store column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('transferred_to_store:', e.message); }
    }
 
    // Add transferred_to_department column for conversation transfer
    if (!existingColumns.includes('transferred_to_department')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN transferred_to_department VARCHAR(100) NULL AFTER transferred_to_store`);
        logger.info('✅ Added transferred_to_department column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('transferred_to_department:', e.message); }
    }
 
    // Add transferred_at column
    if (!existingColumns.includes('transferred_at')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN transferred_at TIMESTAMP NULL AFTER transferred_to_department`);
        logger.info('✅ Added transferred_at column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('transferred_at:', e.message); }
    }
 
    // Add pipeline_stage column for pipeline management
    if (!existingColumns.includes('pipeline_stage')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN pipeline_stage VARCHAR(50) DEFAULT 'unassigned' AFTER transferred_at`);
        logger.info('✅ Added pipeline_stage column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('pipeline_stage:', e.message); }
    }
 
    // Add stage_id column for pipeline management (alias for pipeline_stage)
    if (!existingColumns.includes('stage_id')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN stage_id VARCHAR(50) DEFAULT 'unassigned' AFTER pipeline_stage`);
        logger.info('✅ Added stage_id column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('stage_id:', e.message); }
    }
 
    // Add store_id column for store assignment
    if (!existingColumns.includes('store_id')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN store_id INT NULL AFTER stage_id`);
        logger.info('✅ Added store_id column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('store_id:', e.message); }
    }
 
    // Add department_id column for department assignment
    if (!existingColumns.includes('department_id')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN department_id INT NULL AFTER store_id`);
        logger.info('✅ Added department_id column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('department_id:', e.message); }
    }
 
    // Add transferred_by_user_id column to track who transferred the conversation
    if (!existingColumns.includes('transferred_by_user_id')) {
      try {
        await connection.execute(`ALTER TABLE conversations ADD COLUMN transferred_by_user_id INT NULL AFTER transferred_at`);
        logger.info('✅ Added transferred_by_user_id column to conversations table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('transferred_by_user_id:', e.message); }
    }
 
    // Create messages table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        conversation_id INT,
        phone_number VARCHAR(20) NOT NULL,
        message_text TEXT,
        message_type ENUM('text', 'image', 'audio', 'video', 'document', 'location') DEFAULT 'text',
        media_url VARCHAR(500),
        is_from_bot BOOLEAN DEFAULT FALSE,
        sender_user_id INT,
        timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE,
        FOREIGN KEY (sender_user_id) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_phone (phone_number),
        INDEX idx_timestamp (timestamp),
        INDEX idx_is_from_bot (is_from_bot)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ messages table created/verified');
 
    // Create faqs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS faqs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        instance_id INT NULL,
        question VARCHAR(500) NOT NULL,
        answer TEXT NOT NULL,
        category VARCHAR(50) DEFAULT 'general',
        keywords TEXT,
        emoji VARCHAR(10),
        placeholder_key VARCHAR(100),
        active BOOLEAN DEFAULT TRUE,
        is_active BOOLEAN DEFAULT TRUE,
        order_position INT DEFAULT 1,
        display_order INT DEFAULT 0,
        reaction_time INT DEFAULT 3,
        response_time INT DEFAULT 7,
        schedule_hours VARCHAR(50) DEFAULT '08:00-18:00',
        schedule_days VARCHAR(200) DEFAULT 'monday,tuesday,wednesday,thursday,friday,saturday',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_instance (instance_id),
        INDEX idx_active (active),
        INDEX idx_is_active (is_active),
        INDEX idx_order (order_position),
        INDEX idx_category (category)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ faqs table created/verified');
 
    // Add instance_id column to faqs if it doesn't exist
    try {
      await connection.execute(`ALTER TABLE faqs ADD COLUMN instance_id INT NULL AFTER tenant_id`);
      logger.info('✅ Added instance_id column to faqs table');
    } catch (e) {
      if (e.code !== 'ER_DUP_FIELDNAME') {
        logger.warn('faqs instance_id column:', e.message);
      }
    }
 
    // Add index for instance_id in faqs
    try {
      await connection.execute(`CREATE INDEX idx_instance ON faqs(instance_id)`);
      logger.info('✅ Added index for instance_id in faqs table');
    } catch (e) {
      if (e.code !== 'ER_DUP_KEYNAME') {
        logger.warn('faqs instance_id index:', e.message);
      }
    }
 
    // Create welcome_messages table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS welcome_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        instance_id INT NULL,
        message_text TEXT,
        order_position INT DEFAULT 1,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_instance (instance_id),
        INDEX idx_active (active),
        INDEX idx_order (order_position)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ welcome_messages table created/verified');
 
    // Add instance_id column to welcome_messages if it doesn't exist
    try {
      await connection.execute(`ALTER TABLE welcome_messages ADD COLUMN instance_id INT NULL AFTER tenant_id`);
      logger.info('✅ Added instance_id column to welcome_messages table');
    } catch (e) {
      if (e.code !== 'ER_DUP_FIELDNAME') {
        logger.warn('welcome_messages instance_id column:', e.message);
      }
    }
 
    // Add index for instance_id in welcome_messages
    try {
      await connection.execute(`CREATE INDEX idx_instance ON welcome_messages(instance_id)`);
      logger.info('✅ Added index for instance_id in welcome_messages table');
    } catch (e) {
      if (e.code !== 'ER_DUP_KEYNAME') {
        logger.warn('welcome_messages instance_id index:', e.message);
      }
    }
 
    // Create welcome_sent table (tracks when welcome messages were sent)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS welcome_sent (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        phone_number VARCHAR(20) NOT NULL,
        sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_phone (tenant_id, phone_number),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant_phone (tenant_id, phone_number),
        INDEX idx_sent_at (sent_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ welcome_sent table created/verified');
 
    // Create message_placeholders table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS message_placeholders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        placeholder_key VARCHAR(100) NOT NULL,
        placeholder_value TEXT,
        description TEXT,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_placeholder (tenant_id, placeholder_key),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ message_placeholders table created/verified');
 
    // Create bot_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS bot_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        setting_key VARCHAR(100) NOT NULL,
        setting_value TEXT,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_setting (tenant_id, setting_key),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_setting_key (setting_key)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ bot_settings table created/verified');
 
    // Create contact_groups table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS contact_groups (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        group_name VARCHAR(100) NOT NULL,
        description TEXT,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_group (tenant_id, group_name),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_name (group_name)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ contact_groups table created/verified');
 
    // Create contacts table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS contacts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(100) NOT NULL,
        phone VARCHAR(20) NOT NULL,
        email VARCHAR(100),
        group_id INT,
        tags VARCHAR(255),
        notes TEXT,
        custom_fields JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_phone (tenant_id, phone),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (group_id) REFERENCES contact_groups(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_phone (phone),
        INDEX idx_name (name),
        INDEX idx_group (group_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ contacts table created/verified');
 
    // Create contact_group_members table (many-to-many)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS contact_group_members (
        id INT AUTO_INCREMENT PRIMARY KEY,
        contact_id INT NOT NULL,
        group_id INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_contact_group (contact_id, group_id),
        FOREIGN KEY (contact_id) REFERENCES contacts(id) ON DELETE CASCADE,
        FOREIGN KEY (group_id) REFERENCES contact_groups(id) ON DELETE CASCADE,
        INDEX idx_contact (contact_id),
        INDEX idx_group (group_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ contact_group_members table created/verified');
 
    // Create tags table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tags (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(50) NOT NULL,
        color VARCHAR(7) DEFAULT '#3498db',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_tag (tenant_id, name),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tags table created/verified');
 
    // Create contact_tags table (many-to-many)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS contact_tags (
        id INT AUTO_INCREMENT PRIMARY KEY,
        contact_id INT NOT NULL,
        tag_id INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_contact_tag (contact_id, tag_id),
        FOREIGN KEY (contact_id) REFERENCES contacts(id) ON DELETE CASCADE,
        FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE,
        INDEX idx_contact (contact_id),
        INDEX idx_tag (tag_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ contact_tags table created/verified');
 
    // Create mass_messages table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS mass_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        message_text TEXT NOT NULL,
        media_url VARCHAR(500),
        message_type ENUM('text', 'image', 'audio', 'video') DEFAULT 'text',
        total_contacts INT DEFAULT 0,
        sent_count INT DEFAULT 0,
        status ENUM('pending', 'sending', 'completed', 'failed') DEFAULT 'pending',
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ mass_messages table created/verified');
 
    // Create tenant_payment_methods table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tenant_payment_methods (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        method_name ENUM('paypal', 'pagbank', 'stripe') NOT NULL,
        api_key TEXT,
        api_secret TEXT,
        sandbox_mode BOOLEAN DEFAULT TRUE,
        active BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        UNIQUE KEY unique_tenant_method (tenant_id, method_name),
        INDEX idx_tenant (tenant_id),
        INDEX idx_method (method_name),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tenant_payment_methods table created/verified');
 
    // Create tenant_payment_links table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tenant_payment_links (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        payment_method ENUM('paypal', 'pagbank', 'stripe') NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        description VARCHAR(255),
        customer_phone VARCHAR(20),
        customer_name VARCHAR(100),
        payment_url VARCHAR(500),
        payment_id VARCHAR(100),
        status ENUM('pending', 'paid', 'cancelled', 'expired') DEFAULT 'pending',
        created_by INT,
        expires_at TIMESTAMP NULL,
        paid_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_payment_id (payment_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tenant_payment_links table created/verified');
 
    // Create payments table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS payments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        contact_id INT,
        amount DECIMAL(10, 2) NOT NULL,
        currency VARCHAR(3) DEFAULT 'USD',
        payment_method VARCHAR(50) NOT NULL,
        status ENUM('pending', 'completed', 'failed', 'refunded') DEFAULT 'pending',
        description TEXT,
        external_id VARCHAR(255),
        metadata JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (contact_id) REFERENCES contacts(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_contact (contact_id),
        INDEX idx_status (status),
        INDEX idx_external_id (external_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ payments table created/verified');
 
    // Create plan_addons table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS plan_addons (
        id INT AUTO_INCREMENT PRIMARY KEY,
        resource_key VARCHAR(50) UNIQUE NOT NULL,
        resource_name VARCHAR(100) NOT NULL,
        description TEXT,
        unit_price DECIMAL(10,2) NOT NULL,
        currency VARCHAR(3) DEFAULT 'USD',
        stripe_price_id VARCHAR(255),
        paypal_plan_id VARCHAR(255),
        sort_order INT DEFAULT 0,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_resource_key (resource_key),
        INDEX idx_active (active),
        INDEX idx_sort_order (sort_order)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ plan_addons table created/verified');
 
    // Create addon_purchases table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS addon_purchases (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        addon_id INT NOT NULL,
        quantity INT NOT NULL DEFAULT 1,
        unit_price DECIMAL(10,2) NOT NULL,
        total_amount DECIMAL(10,2) NOT NULL,
        currency VARCHAR(3) DEFAULT 'USD',
        status ENUM('pending', 'completed', 'paid', 'cancelled') DEFAULT 'pending',
        payment_method ENUM('cash', 'transfer', 'pix', 'stripe', 'paypal') DEFAULT 'cash',
        payment_proof VARCHAR(500),
        notes TEXT,
        approved_by INT,
        approved_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (addon_id) REFERENCES plan_addons(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_addon (addon_id),
        INDEX idx_status (status),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ addon_purchases table created/verified');
 
    // Insert default WhatsApp Instances addon if not exists
    const [existingAddon] = await connection.query(
      'SELECT id FROM plan_addons WHERE resource_key = ?',
      ['whatsapp_instances']
    );
    
    if (existingAddon.length === 0) {
      await connection.execute(`
        INSERT INTO plan_addons 
        (resource_key, resource_name, description, unit_price, currency, sort_order, active)
        VALUES (?, ?, ?, ?, ?, ?, ?)
      `, [
        'whatsapp_instances',
        'WhatsApp Instance',
        'Additional WhatsApp instance for connecting more numbers',
        10.00,
        'USD',
        1,
        true
      ]);
      logger.info('✅ Default WhatsApp Instances addon created');
    }
 
    // Create invoice_clients table (must be created before invoices)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS invoice_clients (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(100) NOT NULL,
        email VARCHAR(255) NOT NULL,
        phone VARCHAR(20) NOT NULL,
        company_name VARCHAR(150),
        tax_id VARCHAR(50),
        address VARCHAR(500),
        city VARCHAR(100),
        state VARCHAR(50),
        zip_code VARCHAR(20),
        country VARCHAR(50) DEFAULT 'Brazil',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_email (tenant_id, email),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_email (email),
        INDEX idx_phone (phone),
        INDEX idx_name (name)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ invoice_clients table created/verified');
 
    // Create invoices table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS invoices (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        invoice_number VARCHAR(50) NOT NULL,
        type ENUM('invoice', 'quote') NOT NULL DEFAULT 'invoice',
        client_id INT NOT NULL,
        title VARCHAR(200) NOT NULL,
        description TEXT,
        currency VARCHAR(3) DEFAULT 'USD',
        subtotal DECIMAL(10,2) DEFAULT 0.00,
        tax_rate DECIMAL(5,2) DEFAULT 0.00,
        tax_amount DECIMAL(10,2) DEFAULT 0.00,
        discount_type ENUM('fixed', 'percentage') DEFAULT 'fixed',
        discount_value DECIMAL(10,2) DEFAULT 0.00,
        discount_amount DECIMAL(10,2) DEFAULT 0.00,
        total_amount DECIMAL(10,2) DEFAULT 0.00,
        status ENUM('draft', 'sent', 'viewed', 'accepted', 'rejected', 'paid', 'cancelled', 'archived') DEFAULT 'draft',
        rejection_reason TEXT,
        payment_method ENUM('paypal', 'pagseguro', 'bank_transfer', 'cash', 'other') DEFAULT 'paypal',
        payment_link VARCHAR(500),
        payment_id VARCHAR(100),
        payment_gateway_response JSON,
        due_date DATE,
        notes TEXT,
        terms TEXT,
        sent_at TIMESTAMP NULL,
        viewed_at TIMESTAMP NULL,
        accepted_at TIMESTAMP NULL,
        rejected_at TIMESTAMP NULL,
        paid_at TIMESTAMP NULL,
        converted_to_invoice_id INT,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_invoice (tenant_id, invoice_number),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (client_id) REFERENCES invoice_clients(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_invoice_number (invoice_number),
        INDEX idx_client (client_id),
        INDEX idx_status (status),
        INDEX idx_type (type),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ invoices table created/verified');
 
    // Add new columns to invoices table for enhanced workflow
    const [invoiceColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'invoices'
    `);
    const existingInvoiceColumns = invoiceColumns.map(col => col.COLUMN_NAME);
 
    // Add is_active column for soft disable
    if (!existingInvoiceColumns.includes('is_active')) {
      try {
        await connection.execute(`
          ALTER TABLE invoices 
          ADD COLUMN is_active BOOLEAN DEFAULT TRUE AFTER status
        `);
        logger.info('✅ Added is_active column to invoices table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('is_active column:', e.message);
        }
      }
    }
 
    // Add admin_response column for tenant response to rejection
    if (!existingInvoiceColumns.includes('admin_response')) {
      try {
        await connection.execute(`
          ALTER TABLE invoices 
          ADD COLUMN admin_response TEXT AFTER rejection_reason
        `);
        logger.info('✅ Added admin_response column to invoices table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('admin_response column:', e.message);
        }
      }
    }
 
    // Add admin_response_at column
    if (!existingInvoiceColumns.includes('admin_response_at')) {
      try {
        await connection.execute(`
          ALTER TABLE invoices 
          ADD COLUMN admin_response_at TIMESTAMP NULL AFTER admin_response
        `);
        logger.info('✅ Added admin_response_at column to invoices table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('admin_response_at column:', e.message);
        }
      }
    }
 
    // Add payment_gateway column to store which gateway to use
    if (!existingInvoiceColumns.includes('payment_gateway')) {
      try {
        await connection.execute(`
          ALTER TABLE invoices 
          ADD COLUMN payment_gateway VARCHAR(50) DEFAULT 'stripe' AFTER payment_method
        `);
        logger.info('✅ Added payment_gateway column to invoices table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('payment_gateway column:', e.message);
        }
      }
    }
 
    // Add archived_at column
    if (!existingInvoiceColumns.includes('archived_at')) {
      try {
        await connection.execute(`
          ALTER TABLE invoices 
          ADD COLUMN archived_at TIMESTAMP NULL AFTER paid_at
        `);
        logger.info('✅ Added archived_at column to invoices table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('archived_at column:', e.message);
        }
      }
    }
 
    // Add disabled_at column
    if (!existingInvoiceColumns.includes('disabled_at')) {
      try {
        await connection.execute(`
          ALTER TABLE invoices 
          ADD COLUMN disabled_at TIMESTAMP NULL AFTER archived_at
        `);
        logger.info('✅ Added disabled_at column to invoices table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('disabled_at column:', e.message);
        }
      }
    }
 
    // Add allowed_payment_methods column for storing which payment methods are enabled for this invoice
    if (!existingInvoiceColumns.includes('allowed_payment_methods')) {
      try {
        await connection.execute(`
          ALTER TABLE invoices 
          ADD COLUMN allowed_payment_methods JSON DEFAULT NULL AFTER payment_method
        `);
        logger.info('✅ Added allowed_payment_methods column to invoices table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('allowed_payment_methods column:', e.message);
        }
      }
    }
 
    // Update invoice_logs action enum to include new actions
    try {
      await connection.execute(`
        ALTER TABLE invoice_logs 
        MODIFY COLUMN action ENUM(
          'created', 'sent', 'viewed', 'accepted', 'rejected', 'paid', 
          'cancelled', 'updated', 'payment_created', 'payment_confirmed', 
          'converted_to_invoice', 'archived', 'reactivated', 'disabled', 
          'enabled', 'admin_responded', 'pending_review'
        ) NOT NULL
      `);
      logger.info('✅ Updated invoice_logs action enum');
    } catch (e) {
      logger.warn('invoice_logs action enum update:', e.message);
    }
 
    // Create ai_configurations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS ai_configurations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        evolution_instance_id INT NULL,
        persona_name VARCHAR(100) NOT NULL,
        persona_description TEXT,
        provider ENUM('openai', 'deepseek', 'gpt') NOT NULL DEFAULT 'deepseek',
        model_name VARCHAR(50) NOT NULL,
        api_key TEXT NOT NULL,
        system_prompt TEXT NOT NULL,
        temperature DECIMAL(3,2) DEFAULT 0.70,
        max_tokens INT DEFAULT 1000,
        business_hours_start TIME DEFAULT '08:00:00',
        business_hours_end TIME DEFAULT '18:00:00',
        business_days VARCHAR(100) DEFAULT 'monday,tuesday,wednesday,thursday,friday',
        out_of_hours_message TEXT,
        auto_response_enabled BOOLEAN DEFAULT TRUE,
        response_delay INT DEFAULT 0,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_instance (evolution_instance_id),
        INDEX idx_provider (provider),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ ai_configurations table created/verified');
 
    // Add evolution_instance_id column if it doesn't exist (for existing databases)
    // NOTE: Foreign key constraint will be added after evolution_instances table is created
    const [aiConfigColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'ai_configurations'
    `);
    const existingAIConfigColumns = aiConfigColumns.map(col => col.COLUMN_NAME);
 
    if (!existingAIConfigColumns.includes('evolution_instance_id')) {
      try {
        await connection.execute(`
          ALTER TABLE ai_configurations 
          ADD COLUMN evolution_instance_id INT NULL AFTER tenant_id
        `);
        logger.info('✅ Added evolution_instance_id column to ai_configurations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('evolution_instance_id column:', e.message);
        }
      }
    }
 
    // Add context_messages column for conversation history
    if (!existingAIConfigColumns.includes('context_messages')) {
      try {
        await connection.execute(`
          ALTER TABLE ai_configurations 
          ADD COLUMN context_messages INT DEFAULT 10 AFTER max_tokens
        `);
        logger.info('✅ Added context_messages column to ai_configurations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('context_messages column:', e.message);
        }
      }
    }
 
    // NOTE: Unique constraint and foreign key will be added after evolution_instances table is created
 
    // Create woocommerce_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS woocommerce_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        store_url VARCHAR(255) NOT NULL,
        consumer_key VARCHAR(255) NOT NULL,
        consumer_secret VARCHAR(255) NOT NULL,
        is_active BOOLEAN DEFAULT TRUE,
        last_sync TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_active (is_active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ woocommerce_settings table created/verified');
 
    // Create woocommerce_products table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS woocommerce_products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        wc_product_id INT NOT NULL,
        name VARCHAR(255) NOT NULL,
        slug VARCHAR(255),
        permalink VARCHAR(500),
        description TEXT,
        short_description TEXT,
        sku VARCHAR(100),
        price DECIMAL(10,2) DEFAULT 0.00,
        regular_price DECIMAL(10,2) DEFAULT 0.00,
        sale_price DECIMAL(10,2) DEFAULT 0.00,
        stock_quantity INT DEFAULT 0,
        stock_status VARCHAR(50) DEFAULT 'instock',
        image_url VARCHAR(500),
        thumbnail_url VARCHAR(500),
        categories JSON,
        tags JSON,
        attributes JSON,
        placeholder_key VARCHAR(100),
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_product (tenant_id, wc_product_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_wc_product (wc_product_id),
        INDEX idx_sku (sku),
        INDEX idx_active (is_active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ woocommerce_products table created/verified');
 
    // Create woocommerce_notification_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS woocommerce_notification_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        webhook_secret VARCHAR(255) DEFAULT NULL,
        new_order_enabled BOOLEAN DEFAULT FALSE,
        new_order_template TEXT,
        customer_registration_enabled BOOLEAN DEFAULT FALSE,
        customer_registration_template TEXT,
        password_reset_enabled BOOLEAN DEFAULT FALSE,
        password_reset_template TEXT,
        product_comment_enabled BOOLEAN DEFAULT FALSE,
        product_comment_template TEXT,
        admin_phone VARCHAR(20),
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_active (is_active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ woocommerce_notification_settings table created/verified');
 
    // ============================================
    // Add missing columns to subscription_plans (from migrations)
    // ============================================
    const [planColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'subscription_plans'
    `);
    const existingPlanColumns = planColumns.map(col => col.COLUMN_NAME);
 
    // Add api_access_enabled
    if (!existingPlanColumns.includes('api_access_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN api_access_enabled BOOLEAN DEFAULT FALSE AFTER priority_support_enabled`);
        logger.info('✅ Added api_access_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('api_access_enabled:', e.message); }
    }
 
    // Add woocommerce_enabled
    if (!existingPlanColumns.includes('woocommerce_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN woocommerce_enabled BOOLEAN DEFAULT FALSE AFTER ai_enabled`);
        logger.info('✅ Added woocommerce_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('woocommerce_enabled:', e.message); }
    }
 
    // Add invoices_enabled
    if (!existingPlanColumns.includes('invoices_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN invoices_enabled BOOLEAN DEFAULT FALSE AFTER custom_branding_enabled`);
        logger.info('✅ Added invoices_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('invoices_enabled:', e.message); }
    }
 
    // Add quotes_enabled
    if (!existingPlanColumns.includes('quotes_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN quotes_enabled BOOLEAN DEFAULT FALSE AFTER max_invoices_per_month`);
        logger.info('✅ Added quotes_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('quotes_enabled:', e.message); }
    }
 
    // Add widgets_enabled
    if (!existingPlanColumns.includes('widgets_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN widgets_enabled BOOLEAN DEFAULT FALSE AFTER max_quotes_per_month`);
        logger.info('✅ Added widgets_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('widgets_enabled:', e.message); }
    }
 
    // Add payment_links_enabled
    if (!existingPlanColumns.includes('payment_links_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN payment_links_enabled BOOLEAN DEFAULT FALSE AFTER max_widgets`);
        logger.info('✅ Added payment_links_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('payment_links_enabled:', e.message); }
    }
 
    // Add biolink fields to subscription_plans
    if (!existingPlanColumns.includes('biolink_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN biolink_enabled BOOLEAN DEFAULT FALSE AFTER payment_links_enabled`);
        logger.info('✅ Added biolink_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_enabled:', e.message); }
    }
 
    if (!existingPlanColumns.includes('max_bio_pages')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_bio_pages INT DEFAULT 0 AFTER biolink_enabled`);
        logger.info('✅ Added max_bio_pages to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_bio_pages:', e.message); }
    }
 
    if (!existingPlanColumns.includes('max_short_links')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_short_links INT DEFAULT 0 AFTER max_bio_pages`);
        logger.info('✅ Added max_short_links to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_short_links:', e.message); }
    }
 
    if (!existingPlanColumns.includes('max_file_transfers')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_file_transfers INT DEFAULT 0 AFTER max_short_links`);
        logger.info('✅ Added max_file_transfers to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_file_transfers:', e.message); }
    }
 
    if (!existingPlanColumns.includes('max_vcards')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_vcards INT DEFAULT 0 AFTER max_file_transfers`);
        logger.info('✅ Added max_vcards to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_vcards:', e.message); }
    }
 
    if (!existingPlanColumns.includes('max_event_links')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_event_links INT DEFAULT 0 AFTER max_vcards`);
        logger.info('✅ Added max_event_links to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_event_links:', e.message); }
    }
 
    if (!existingPlanColumns.includes('max_html_pages')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_html_pages INT DEFAULT 0 AFTER max_event_links`);
        logger.info('✅ Added max_html_pages to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_html_pages:', e.message); }
    }
 
    if (!existingPlanColumns.includes('max_qr_codes')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN max_qr_codes INT DEFAULT 0 AFTER max_html_pages`);
        logger.info('✅ Added max_qr_codes to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_qr_codes:', e.message); }
    }
 
    // Add pix_enabled
    if (!existingPlanColumns.includes('pix_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN pix_enabled BOOLEAN DEFAULT FALSE AFTER payment_links_enabled`);
        logger.info('✅ Added pix_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('pix_enabled:', e.message); }
    }
 
    // Add cash_enabled
    if (!existingPlanColumns.includes('cash_enabled')) {
      try {
        await connection.execute(`ALTER TABLE subscription_plans ADD COLUMN cash_enabled BOOLEAN DEFAULT FALSE AFTER pix_enabled`);
        logger.info('✅ Added cash_enabled to subscription_plans');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('cash_enabled:', e.message); }
    }
 
    // ============================================
    // Add missing columns to payments table (from migrations)
    // ============================================
    const [paymentColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'payments'
    `);
    const existingPaymentColumns = paymentColumns.map(col => col.COLUMN_NAME);
 
    if (!existingPaymentColumns.includes('plan_id')) {
      try {
        await connection.execute(`ALTER TABLE payments ADD COLUMN plan_id INT NULL AFTER tenant_id`);
        logger.info('✅ Added plan_id to payments');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('plan_id:', e.message); }
    }
 
    if (!existingPaymentColumns.includes('subscription_id')) {
      try {
        await connection.execute(`ALTER TABLE payments ADD COLUMN subscription_id INT NULL AFTER plan_id`);
        logger.info('✅ Added subscription_id to payments');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('subscription_id:', e.message); }
    }
 
    // ============================================
    // Add missing columns to payment_gateway_settings (from migrations)
    // ============================================
    const [gatewayColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'payment_gateway_settings'
    `);
    const existingGatewayColumns = gatewayColumns.map(col => col.COLUMN_NAME);
 
    if (!existingGatewayColumns.includes('paypal_webhook_id')) {
      try {
        await connection.execute(`ALTER TABLE payment_gateway_settings ADD COLUMN paypal_webhook_id VARCHAR(255) AFTER paypal_mode`);
        logger.info('✅ Added paypal_webhook_id to payment_gateway_settings');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('paypal_webhook_id:', e.message); }
    }
 
    if (!existingGatewayColumns.includes('cash_instructions')) {
      try {
        await connection.execute(`ALTER TABLE payment_gateway_settings ADD COLUMN cash_instructions TEXT AFTER paypal_webhook_id`);
        logger.info('✅ Added cash_instructions to payment_gateway_settings');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('cash_instructions:', e.message); }
    }
 
    if (!existingGatewayColumns.includes('cash_contact_email')) {
      try {
        await connection.execute(`ALTER TABLE payment_gateway_settings ADD COLUMN cash_contact_email VARCHAR(255) AFTER cash_instructions`);
        logger.info('✅ Added cash_contact_email to payment_gateway_settings');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('cash_contact_email:', e.message); }
    }
 
    if (!existingGatewayColumns.includes('cash_contact_phone')) {
      try {
        await connection.execute(`ALTER TABLE payment_gateway_settings ADD COLUMN cash_contact_phone VARCHAR(20) AFTER cash_contact_email`);
        logger.info('✅ Added cash_contact_phone to payment_gateway_settings');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('cash_contact_phone:', e.message); }
    }
 
    if (!existingGatewayColumns.includes('stripe_mode')) {
      try {
        await connection.execute(`ALTER TABLE payment_gateway_settings ADD COLUMN stripe_mode ENUM('test', 'live') DEFAULT 'test' AFTER stripe_webhook_secret`);
        logger.info('✅ Added stripe_mode to payment_gateway_settings');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('stripe_mode:', e.message); }
    }
 
    // ============================================
    // Add missing columns to whatsapp_notification_settings (from migrations)
    // ============================================
    const [waNotifColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_notification_settings'
    `);
    const existingWaNotifColumns = waNotifColumns.map(col => col.COLUMN_NAME);
 
    if (!existingWaNotifColumns.includes('qr_code')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_notification_settings ADD COLUMN qr_code TEXT AFTER connected`);
        logger.info('✅ Added qr_code to whatsapp_notification_settings');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('qr_code:', e.message); }
    }
 
    // ============================================
    // Add missing columns to tenants table (from migrations)
    // ============================================
    const [tenantColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'tenants'
    `);
    const existingTenantColumns = tenantColumns.map(col => col.COLUMN_NAME);
 
    // Add max_contact_groups
    if (!existingTenantColumns.includes('max_contact_groups')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_contact_groups INT DEFAULT 10 AFTER max_devices`);
        logger.info('✅ Added max_contact_groups to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_contact_groups:', e.message); }
    }
 
    // Add Bio Link columns to tenants
    if (!existingTenantColumns.includes('max_bio_pages')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_bio_pages INT DEFAULT 0 AFTER max_omnichannel_accounts`);
        logger.info('✅ Added max_bio_pages to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_bio_pages:', e.message); }
    }
 
    if (!existingTenantColumns.includes('max_short_links')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_short_links INT DEFAULT 0 AFTER max_bio_pages`);
        logger.info('✅ Added max_short_links to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_short_links:', e.message); }
    }
 
    if (!existingTenantColumns.includes('max_file_transfers')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_file_transfers INT DEFAULT 0 AFTER max_short_links`);
        logger.info('✅ Added max_file_transfers to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_file_transfers:', e.message); }
    }
 
    if (!existingTenantColumns.includes('max_vcards')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_vcards INT DEFAULT 0 AFTER max_file_transfers`);
        logger.info('✅ Added max_vcards to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_vcards:', e.message); }
    }
 
    if (!existingTenantColumns.includes('max_event_links')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_event_links INT DEFAULT 0 AFTER max_vcards`);
        logger.info('✅ Added max_event_links to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_event_links:', e.message); }
    }
 
    if (!existingTenantColumns.includes('max_html_pages')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_html_pages INT DEFAULT 0 AFTER max_event_links`);
        logger.info('✅ Added max_html_pages to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_html_pages:', e.message); }
    }
 
    if (!existingTenantColumns.includes('max_qr_codes')) {
      try {
        await connection.execute(`ALTER TABLE tenants ADD COLUMN max_qr_codes INT DEFAULT 0 AFTER max_html_pages`);
        logger.info('✅ Added max_qr_codes to tenants');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('max_qr_codes:', e.message); }
    }
 
    // Insert default super admin
    const [superAdminExists] = await connection.execute(
      'SELECT id FROM super_admins WHERE email = ?',
      [process.env.SUPER_ADMIN_EMAIL || 'admin@saas.misayan.cloud']
    );
 
    if (superAdminExists.length === 0) {
      const hashedPassword = await bcrypt.hash(
        process.env.SUPER_ADMIN_PASSWORD || 'ChangeThisPassword123!',
        12
      );
      await connection.execute(
        'INSERT INTO super_admins (email, password, name) VALUES (?, ?, ?)',
        [
          process.env.SUPER_ADMIN_EMAIL || 'admin@saas.misayan.cloud',
          hashedPassword,
          'Super Administrator'
        ]
      );
      logger.info('✅ Super Admin created');
      logger.info(`📧 Email: ${process.env.SUPER_ADMIN_EMAIL || 'admin@saas.misayan.cloud'}`);
      logger.info(`🔑 Password: ${process.env.SUPER_ADMIN_PASSWORD || 'ChangeThisPassword123!'}`);
      logger.warn('⚠️  IMPORTANT: Change the super admin password immediately!');
    } else {
      logger.info('✅ Super Admin already exists');
    }
 
    // Insert default currencies
    const defaultCurrencies = [
      ['USD', 'US Dollar', '$', 1.0000, true, true],
      ['EUR', 'Euro', '€', 0.92, true, false],
      ['GBP', 'British Pound', '£', 0.79, true, false],
      ['BRL', 'Brazilian Real', 'R$', 4.97, true, false]
    ];
 
    for (const [code, name, symbol, rate, active, isDefault] of defaultCurrencies) {
      await connection.execute(
        `INSERT IGNORE INTO currencies (code, name, symbol, exchange_rate, active, is_default) 
         VALUES (?, ?, ?, ?, ?, ?)`,
        [code, name, symbol, rate, active, isDefault]
      );
    }
    logger.info('✅ Default currencies created/verified');
 
    // Create subscriptions table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS subscriptions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        plan_id INT NOT NULL,
        status ENUM('active', 'cancelled', 'past_due', 'trialing', 'suspended') DEFAULT 'active',
        stripe_subscription_id VARCHAR(255),
        stripe_customer_id VARCHAR(255),
        paypal_subscription_id VARCHAR(255),
        current_period_start TIMESTAMP NULL,
        current_period_end TIMESTAMP NULL,
        cancel_at_period_end BOOLEAN DEFAULT FALSE,
        cancelled_at TIMESTAMP NULL,
        trial_start TIMESTAMP NULL,
        trial_end TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (plan_id) REFERENCES subscription_plans(id),
        INDEX idx_tenant (tenant_id),
        INDEX idx_plan (plan_id),
        INDEX idx_status (status),
        INDEX idx_stripe_subscription (stripe_subscription_id),
        INDEX idx_paypal_subscription (paypal_subscription_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ subscriptions table created/verified');
 
    // Create usage_tracking table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS usage_tracking (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        month VARCHAR(7) NOT NULL,
        messages_sent INT DEFAULT 0,
        conversations_count INT DEFAULT 0,
        contacts_count INT DEFAULT 0,
        users_count INT DEFAULT 0,
        stores_count INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_month (tenant_id, month),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_month (month)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ usage_tracking table created/verified');
 
    // Create system_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS system_settings (
        id INT PRIMARY KEY DEFAULT 1,
        grace_period_days INT DEFAULT 7,
        payment_reminder_days VARCHAR(50) DEFAULT '7,3,2,1',
        overdue_reminder_interval_days INT DEFAULT 2,
        auto_suspend_enabled BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ system_settings table created/verified');
 
    // Insert default system settings
    await connection.execute(`
      INSERT IGNORE INTO system_settings (id, grace_period_days) VALUES (1, 7)
    `);
 
    // Create system_settings_kv table (key-value store for additional settings)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS system_settings_kv (
        id INT AUTO_INCREMENT PRIMARY KEY,
        setting_key VARCHAR(100) NOT NULL UNIQUE,
        setting_value TEXT,
        description VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_setting_key (setting_key)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ system_settings_kv table created/verified');
 
    // Insert default key-value settings
    const defaultKvSettings = [
      ['default_language', 'en', 'Default system language code'],
      ['system_name', 'Misayan SaaS', 'System name displayed in UI'],
      ['system_email', 'noreply@misayan.com', 'System email for notifications'],
      ['maintenance_mode', '0', 'Enable/disable maintenance mode (0=off, 1=on)'],
      ['allow_registration', '1', 'Allow new tenant registration (0=no, 1=yes)'],
      ['superadmin_whatsapp_phone', '', 'SuperAdmin WhatsApp phone for payment support'],
      ['superadmin_support_email', '', 'SuperAdmin support email']
    ];
 
    for (const [key, value, desc] of defaultKvSettings) {
      await connection.execute(`
        INSERT IGNORE INTO system_settings_kv (setting_key, setting_value, description)
        VALUES (?, ?, ?)
      `, [key, value, desc]);
    }
    logger.info('✅ Default system settings (key-value) created/verified');
 
    // Create payment_gateway_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS payment_gateway_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        gateway_name ENUM('stripe', 'paypal', 'pagbank', 'cash', 'pix') NOT NULL UNIQUE,
        stripe_secret_key TEXT,
        stripe_publishable_key TEXT,
        stripe_webhook_secret TEXT,
        stripe_mode ENUM('test', 'live') DEFAULT 'test',
        paypal_client_id TEXT,
        paypal_client_secret TEXT,
        paypal_mode ENUM('sandbox', 'live') DEFAULT 'sandbox',
        paypal_webhook_id VARCHAR(255),
        pagbank_token TEXT,
        pagbank_email VARCHAR(255),
        pagbank_mode ENUM('sandbox', 'live') DEFAULT 'sandbox',
        cash_instructions TEXT,
        cash_contact_email VARCHAR(255),
        cash_contact_phone VARCHAR(20),
        enabled BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_gateway (gateway_name),
        INDEX idx_enabled (enabled)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ payment_gateway_settings table created/verified');
 
    // Insert default PIX gateway if not exists
    await connection.execute(`
      INSERT IGNORE INTO payment_gateway_settings (gateway_name, enabled, cash_instructions)
      VALUES ('pix', FALSE, 'Contact via WhatsApp to receive PIX payment instructions.')
    `);
    logger.info('✅ PIX gateway default settings created/verified');
 
    // Update cash gateway with default instructions if empty
    await connection.execute(`
      UPDATE payment_gateway_settings 
      SET cash_instructions = 'Contact via WhatsApp to complete cash payment.'
      WHERE gateway_name = 'cash' AND (cash_instructions IS NULL OR cash_instructions = '')
    `);
    logger.info('✅ Cash gateway default instructions updated');
 
    // Create smtp_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS smtp_settings (
        id INT PRIMARY KEY DEFAULT 1,
        smtp_host VARCHAR(255),
        smtp_port INT DEFAULT 587,
        smtp_user VARCHAR(255),
        smtp_password TEXT,
        smtp_from_email VARCHAR(255),
        smtp_from_name VARCHAR(100),
        smtp_secure BOOLEAN DEFAULT TRUE,
        enabled BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ smtp_settings table created/verified');
 
    // Create email_templates table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        template_key VARCHAR(100) NOT NULL UNIQUE,
        template_name VARCHAR(150) NOT NULL,
        subject VARCHAR(255) NOT NULL,
        html_body TEXT NOT NULL,
        text_body TEXT NOT NULL,
        available_variables TEXT,
        category ENUM('account', 'billing', 'notification') DEFAULT 'notification',
        is_system BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_template_key (template_key),
        INDEX idx_category (category)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_templates table created/verified');
 
    // Default email templates removed - users will create their own templates
    logger.info('✅ Email templates table ready (no default templates)');
 
    // Create billing_history table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS billing_history (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        plan_id INT NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        currency VARCHAR(3) DEFAULT 'USD',
        payment_method ENUM('stripe', 'paypal', 'manual') NOT NULL,
        transaction_id VARCHAR(255),
        invoice_number VARCHAR(50),
        status ENUM('pending', 'completed', 'failed', 'refunded') DEFAULT 'pending',
        failure_reason TEXT,
        attempt_count INT DEFAULT 0,
        payment_date TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (plan_id) REFERENCES subscription_plans(id),
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_payment_date (payment_date),
        INDEX idx_transaction_id (transaction_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ billing_history table created/verified');
 
    // Create email_queue table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_queue (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        recipient_email VARCHAR(255) NOT NULL,
        recipient_name VARCHAR(100),
        template_key VARCHAR(100) NOT NULL,
        subject VARCHAR(255) NOT NULL,
        html_body TEXT NOT NULL,
        text_body TEXT NOT NULL,
        variables JSON,
        status ENUM('pending', 'sent', 'failed') DEFAULT 'pending',
        attempt_count INT DEFAULT 0,
        last_error TEXT,
        scheduled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        sent_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_status (status),
        INDEX idx_scheduled_at (scheduled_at),
        INDEX idx_tenant (tenant_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_queue table created/verified');
 
    // Create superadmin_activity_log table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS superadmin_activity_log (
        id INT AUTO_INCREMENT PRIMARY KEY,
        super_admin_id INT NOT NULL,
        action VARCHAR(100) NOT NULL,
        resource_type VARCHAR(50),
        resource_id INT,
        details JSON,
        ip_address VARCHAR(45),
        user_agent TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (super_admin_id) REFERENCES super_admins(id) ON DELETE CASCADE,
        INDEX idx_super_admin (super_admin_id),
        INDEX idx_action (action),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ superadmin_activity_log table created/verified');
 
    // Create landing_page_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS landing_page_settings (
        id INT PRIMARY KEY DEFAULT 1,
        landing_enabled BOOLEAN DEFAULT TRUE,
        hero_title VARCHAR(255) DEFAULT 'Transform Your Business with WhatsApp',
        hero_subtitle TEXT DEFAULT 'Powerful multi-tenant WhatsApp Business platform',
        hero_cta_text VARCHAR(100) DEFAULT 'Get Started',
        hero_cta_link VARCHAR(255) DEFAULT '/#plans',
        hero_image VARCHAR(255) DEFAULT '/images/hero.png',
        hero_bg_color VARCHAR(20) DEFAULT '#00a149',
        features_title VARCHAR(255) DEFAULT 'Powerful Features',
        features_subtitle TEXT DEFAULT 'Everything you need to manage WhatsApp Business at scale',
        wa_generator_enabled BOOLEAN DEFAULT TRUE,
        wa_generator_title VARCHAR(255) DEFAULT 'WhatsApp Chat Link Generator',
        wa_generator_subtitle TEXT DEFAULT 'Create custom WhatsApp links with pre-filled messages',
        wa_generator_bg_color VARCHAR(20) DEFAULT '#f8f9fa',
        plans_title VARCHAR(255) DEFAULT 'Choose Your Plan',
        plans_subtitle TEXT DEFAULT 'Flexible pricing for businesses of all sizes',
        plans_show_annual BOOLEAN DEFAULT TRUE,
        testimonials_enabled BOOLEAN DEFAULT TRUE,
        testimonials_title VARCHAR(255) DEFAULT 'What Our Clients Say',
        testimonials_subtitle TEXT DEFAULT 'Join thousands of satisfied customers',
        cta_title VARCHAR(255) DEFAULT 'Ready to Get Started?',
        cta_subtitle TEXT DEFAULT 'Start your free trial today. No credit card required.',
        cta_button_text VARCHAR(100) DEFAULT 'Start Free Trial',
        cta_bg_color VARCHAR(20) DEFAULT '#00a149',
        company_name VARCHAR(100) DEFAULT 'Misayan SaaS',
        company_logo VARCHAR(255),
        primary_color VARCHAR(7) DEFAULT '#00a149',
        secondary_color VARCHAR(7) DEFAULT '#319131',
        accent_color VARCHAR(20) DEFAULT '#25D366',
        text_color VARCHAR(20) DEFAULT '#333333',
        footer_text TEXT DEFAULT '© 2025 Misayan SaaS. All rights reserved.',
        footer_bg_color VARCHAR(20) DEFAULT '#1a202c',
        meta_title VARCHAR(255) DEFAULT 'Misayan SaaS - WhatsApp Business Platform',
        meta_description TEXT DEFAULT 'Complete multi-tenant WhatsApp Business solution',
        meta_keywords TEXT DEFAULT 'whatsapp, business, saas, multi-tenant',
        contact_email VARCHAR(255),
        contact_phone VARCHAR(20),
        social_facebook VARCHAR(255),
        social_twitter VARCHAR(255),
        social_linkedin VARCHAR(255),
        social_instagram VARCHAR(255),
        header_logo VARCHAR(500) DEFAULT NULL COMMENT 'Logo URL for header/navbar',
        hero_logo VARCHAR(500) DEFAULT NULL COMMENT 'Logo URL for hero section',
        footer_logo VARCHAR(500) DEFAULT NULL COMMENT 'Logo URL for footer',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ landing_page_settings table created/verified');
 
    await connection.execute(`
      ALTER TABLE landing_page_settings 
      ADD COLUMN IF NOT EXISTS landing_enabled BOOLEAN DEFAULT TRUE
    `);
 
    // Insert default landing page settings
    await connection.execute(`
      INSERT IGNORE INTO landing_page_settings (id) VALUES (1)
    `);
 
    // Create landing_page_features table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS landing_page_features (
        id INT AUTO_INCREMENT PRIMARY KEY,
        icon VARCHAR(50) NOT NULL,
        title VARCHAR(100) NOT NULL,
        description TEXT NOT NULL,
        sort_order INT DEFAULT 0,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_sort (sort_order),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ landing_page_features table created/verified');
 
    // Insert default features
    const [featuresExist] = await connection.execute('SELECT id FROM landing_page_features LIMIT 1');
    if (featuresExist.length === 0) {
      const defaultFeatures = [
        ['fa-comments', 'Multi-Channel Communication', 'Connect with customers via WhatsApp, SMS, and more', 0],
        ['fa-robot', 'AI-Powered Automation', 'Intelligent chatbots that understand and respond naturally', 1],
        ['fa-chart-line', 'Advanced Analytics', 'Track performance and gain insights into customer behavior', 2],
        ['fa-users', 'Team Collaboration', 'Manage multiple agents and departments efficiently', 3],
        ['fa-shield-alt', 'Enterprise Security', 'Bank-level encryption and data protection', 4],
        ['fa-plug', 'Easy Integration', 'Connect with your existing tools and workflows', 5]
      ];
 
      for (const [icon, title, description, order] of defaultFeatures) {
        await connection.execute(
          'INSERT INTO landing_page_features (icon, title, description, sort_order) VALUES (?, ?, ?, ?)',
          [icon, title, description, order]
        );
      }
      logger.info('✅ Default landing page features created');
    }
 
    // Create landing_page_testimonials table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS landing_page_testimonials (
        id INT AUTO_INCREMENT PRIMARY KEY,
        customer_name VARCHAR(100) NOT NULL,
        customer_title VARCHAR(100),
        customer_company VARCHAR(100),
        customer_avatar VARCHAR(255),
        testimonial_text TEXT NOT NULL,
        rating INT DEFAULT 5,
        sort_order INT DEFAULT 0,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_sort (sort_order),
        INDEX idx_active (active),
        INDEX idx_rating (rating)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ landing_page_testimonials table created/verified');
 
    // ============================================
    // WhatsApp Tables (Direct Creation)
    // ============================================
 
    // Create whatsapp_connections table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_connections (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        phone_number VARCHAR(20),
        status ENUM('disconnected', 'connecting', 'connected', 'failed') DEFAULT 'disconnected',
        qr_code TEXT,
        session_id VARCHAR(255),
        last_connected_at DATETIME,
        connection_attempts INT DEFAULT 0,
        error_message TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_status (status),
        INDEX idx_phone_number (phone_number),
        UNIQUE KEY unique_tenant_connection (tenant_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_connections table created/verified');
 
    // Create whatsapp_messages table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        connection_id INT,
        phone_number VARCHAR(20) NOT NULL,
        contact_name VARCHAR(255),
        message_type ENUM('text', 'image', 'video', 'audio', 'document', 'sticker', 'location', 'contact') DEFAULT 'text',
        content TEXT,
        media_url VARCHAR(500),
        media_mimetype VARCHAR(100),
        media_size INT,
        caption TEXT,
        direction ENUM('incoming', 'outgoing') NOT NULL,
        status ENUM('pending', 'sent', 'delivered', 'read', 'failed') DEFAULT 'pending',
        whatsapp_message_id VARCHAR(255),
        conversation_id INT,
        quoted_message_id INT,
        error_message TEXT,
        metadata JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_connection_id (connection_id),
        INDEX idx_phone_number (phone_number),
        INDEX idx_direction (direction),
        INDEX idx_status (status),
        INDEX idx_created_at (created_at),
        INDEX idx_conversation_id (conversation_id),
        INDEX idx_whatsapp_message_id (whatsapp_message_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_messages table created/verified');
 
    // Add sender info columns to whatsapp_messages table for user/bot identification
    const [waMessageColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_messages'
    `);
    const existingWaMessageColumns = waMessageColumns.map(col => col.COLUMN_NAME);
 
    // Add instance_id column for Evolution API integration
    if (!existingWaMessageColumns.includes('instance_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN instance_id INT NULL AFTER tenant_id`);
        await connection.execute(`CREATE INDEX idx_instance_id ON whatsapp_messages(instance_id)`);
        logger.info('✅ Added instance_id column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME' && e.code !== 'ER_DUP_KEYNAME') logger.warn('instance_id:', e.message); }
    }
 
    // Add sender_user_id column
    if (!existingWaMessageColumns.includes('sender_user_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN sender_user_id INT NULL AFTER metadata`);
        logger.info('✅ Added sender_user_id column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('sender_user_id:', e.message); }
    }
 
    // Add sender_name column
    if (!existingWaMessageColumns.includes('sender_name')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN sender_name VARCHAR(100) NULL AFTER sender_user_id`);
        logger.info('✅ Added sender_name column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('sender_name:', e.message); }
    }
 
    // Add sender_store column
    if (!existingWaMessageColumns.includes('sender_store')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN sender_store VARCHAR(100) NULL AFTER sender_name`);
        logger.info('✅ Added sender_store column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('sender_store:', e.message); }
    }
 
    // Add sender_department column
    if (!existingWaMessageColumns.includes('sender_department')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN sender_department VARCHAR(100) NULL AFTER sender_store`);
        logger.info('✅ Added sender_department column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('sender_department:', e.message); }
    }
 
    // Add is_bot_message column
    if (!existingWaMessageColumns.includes('is_bot_message')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN is_bot_message BOOLEAN DEFAULT FALSE AFTER sender_department`);
        logger.info('✅ Added is_bot_message column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('is_bot_message:', e.message); }
    }
 
    // Add bot_persona_name column
    if (!existingWaMessageColumns.includes('bot_persona_name')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN bot_persona_name VARCHAR(100) NULL AFTER is_bot_message`);
        logger.info('✅ Added bot_persona_name column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('bot_persona_name:', e.message); }
    }
 
    // Add columns for message edit functionality
    if (!existingWaMessageColumns.includes('original_content')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN original_content TEXT NULL AFTER content`);
        logger.info('✅ Added original_content column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('original_content:', e.message); }
    }
 
    if (!existingWaMessageColumns.includes('is_edited')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN is_edited BOOLEAN DEFAULT FALSE AFTER original_content`);
        logger.info('✅ Added is_edited column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('is_edited:', e.message); }
    }
 
    if (!existingWaMessageColumns.includes('edited_at')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN edited_at TIMESTAMP NULL AFTER is_edited`);
        logger.info('✅ Added edited_at column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('edited_at:', e.message); }
    }
 
    // Add columns for message delete functionality
    if (!existingWaMessageColumns.includes('is_deleted')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN is_deleted BOOLEAN DEFAULT FALSE AFTER edited_at`);
        logger.info('✅ Added is_deleted column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('is_deleted:', e.message); }
    }
 
    if (!existingWaMessageColumns.includes('deleted_for_everyone')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN deleted_for_everyone BOOLEAN DEFAULT FALSE AFTER is_deleted`);
        logger.info('✅ Added deleted_for_everyone column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('deleted_for_everyone:', e.message); }
    }
 
    if (!existingWaMessageColumns.includes('deleted_at')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN deleted_at TIMESTAMP NULL AFTER deleted_for_everyone`);
        logger.info('✅ Added deleted_at column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('deleted_at:', e.message); }
    }
 
    if (!existingWaMessageColumns.includes('deleted_by_user_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN deleted_by_user_id INT NULL AFTER deleted_at`);
        logger.info('✅ Added deleted_by_user_id column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('deleted_by_user_id:', e.message); }
    }
 
    if (!existingWaMessageColumns.includes('deleted_for_user_ids')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN deleted_for_user_ids JSON NULL AFTER deleted_by_user_id`);
        logger.info('✅ Added deleted_for_user_ids column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('deleted_for_user_ids:', e.message); }
    }
 
    if (!existingWaMessageColumns.includes('whatsapp_message_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_messages ADD COLUMN whatsapp_message_id VARCHAR(255) NULL AFTER deleted_for_user_ids`);
        await connection.execute(`CREATE INDEX idx_whatsapp_message_id ON whatsapp_messages(whatsapp_message_id)`);
        logger.info('✅ Added whatsapp_message_id column to whatsapp_messages table');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME' && e.code !== 'ER_DUP_KEYNAME') logger.warn('whatsapp_message_id:', e.message); }
    }
 
    // Fix message_type ENUM to support Evolution API message types
    try {
      await connection.execute(`
        ALTER TABLE whatsapp_messages 
        MODIFY COLUMN message_type ENUM(
          'text',
          'image',
          'video',
          'audio',
          'document',
          'sticker',
          'location',
          'contact',
          'conversation',
          'extendedTextMessage',
          'imageMessage',
          'videoMessage',
          'audioMessage',
          'documentMessage',
          'stickerMessage',
          'locationMessage',
          'contactMessage',
          'reactionMessage',
          'pollMessage'
        ) DEFAULT 'text'
      `);
      logger.info('✅ Updated message_type ENUM to support Evolution API message types');
    } catch (e) {
      // Ignore if already updated or other non-critical errors
      if (e.code !== 'ER_DUP_FIELDNAME') {
        logger.warn('message_type ENUM update:', e.message);
      }
    }
 
    // Create whatsapp_contacts table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_contacts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        phone_number VARCHAR(20) NOT NULL,
        name VARCHAR(255),
        profile_picture_url VARCHAR(500),
        status_message TEXT,
        is_business BOOLEAN DEFAULT FALSE,
        is_blocked BOOLEAN DEFAULT FALSE,
        last_message_at DATETIME,
        message_count INT DEFAULT 0,
        metadata JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_phone_number (phone_number),
        INDEX idx_last_message_at (last_message_at),
        UNIQUE KEY unique_tenant_contact (tenant_id, phone_number),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_contacts table created/verified');
 
    // Create whatsapp_message_queue table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_message_queue (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        connection_id INT,
        phone_number VARCHAR(20) NOT NULL,
        message_type ENUM('text', 'image', 'video', 'audio', 'document') DEFAULT 'text',
        content TEXT,
        media_path VARCHAR(500),
        caption TEXT,
        priority INT DEFAULT 0,
        status ENUM('pending', 'processing', 'sent', 'failed') DEFAULT 'pending',
        attempts INT DEFAULT 0,
        max_attempts INT DEFAULT 3,
        scheduled_at DATETIME,
        processed_at DATETIME,
        error_message TEXT,
        metadata JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_connection_id (connection_id),
        INDEX idx_status (status),
        INDEX idx_priority (priority),
        INDEX idx_scheduled_at (scheduled_at),
        INDEX idx_created_at (created_at),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_message_queue table created/verified');
 
    // Create whatsapp_sessions table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_sessions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        session_id VARCHAR(255) NOT NULL,
        session_data LONGTEXT,
        phone_number VARCHAR(20),
        device_info JSON,
        is_active BOOLEAN DEFAULT TRUE,
        last_activity_at DATETIME,
        expires_at DATETIME,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_session_id (session_id),
        INDEX idx_is_active (is_active),
        INDEX idx_expires_at (expires_at),
        UNIQUE KEY unique_tenant_session (tenant_id, session_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_sessions table created/verified');
 
    // Create whatsapp_groups table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_groups (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        connection_id INT,
        group_jid VARCHAR(255) NOT NULL,
        group_name VARCHAR(255),
        group_description TEXT,
        group_picture_url VARCHAR(500),
        participant_count INT DEFAULT 0,
        is_admin BOOLEAN DEFAULT FALSE,
        created_by VARCHAR(20),
        metadata JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_connection_id (connection_id),
        INDEX idx_group_jid (group_jid),
        UNIQUE KEY unique_tenant_group (tenant_id, group_jid),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_groups table created/verified');
 
    // Create whatsapp_webhooks table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_webhooks (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        event_type VARCHAR(50) NOT NULL,
        webhook_url VARCHAR(500) NOT NULL,
        is_active BOOLEAN DEFAULT TRUE,
        secret_key VARCHAR(255),
        retry_count INT DEFAULT 3,
        timeout_seconds INT DEFAULT 30,
        last_triggered_at DATETIME,
        success_count INT DEFAULT 0,
        failure_count INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_event_type (event_type),
        INDEX idx_is_active (is_active),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_webhooks table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tenant_api_keys (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        key_name VARCHAR(120) NOT NULL,
        key_prefix VARCHAR(20) NOT NULL,
        key_hash CHAR(64) NOT NULL,
        is_active BOOLEAN DEFAULT TRUE,
        last_used_at DATETIME,
        revoked_at DATETIME,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_key_prefix (key_prefix),
        INDEX idx_is_active (is_active),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tenant_api_keys table created/verified');
    try {
      const [tenantApiKeyColumns] = await connection.query(`
        SELECT COLUMN_NAME 
        FROM information_schema.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'tenant_api_keys'
      `);
      let existingTenantApiKeyColumns = tenantApiKeyColumns.map(col => col.COLUMN_NAME);
 
      const hasLegacyApiKeys = existingTenantApiKeyColumns.includes('api_key') ||
        existingTenantApiKeyColumns.includes('api_secret') ||
        existingTenantApiKeyColumns.includes('permissions') ||
        existingTenantApiKeyColumns.includes('expires_at') ||
        existingTenantApiKeyColumns.includes('status');
 
      if (hasLegacyApiKeys) {
        try {
          await connection.execute('SET FOREIGN_KEY_CHECKS=0');
          await connection.execute('DROP TABLE IF EXISTS tenant_api_keys_new');
          await connection.execute(`
            CREATE TABLE tenant_api_keys_new (
              id INT AUTO_INCREMENT PRIMARY KEY,
              tenant_id INT NOT NULL,
              key_name VARCHAR(120) NOT NULL,
              key_prefix VARCHAR(20) NOT NULL,
              key_hash CHAR(64) NOT NULL,
              is_active BOOLEAN DEFAULT TRUE,
              last_used_at DATETIME,
              revoked_at DATETIME,
              created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
              updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              INDEX idx_tenant_id (tenant_id),
              INDEX idx_key_prefix (key_prefix),
              INDEX idx_is_active (is_active),
              FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
          `);
          await connection.execute(`
            INSERT INTO tenant_api_keys_new (id, tenant_id, key_name, key_prefix, key_hash, is_active, last_used_at, revoked_at, created_at, updated_at)
            SELECT id, tenant_id, key_name, key_prefix, key_hash, is_active, last_used_at, revoked_at, created_at, updated_at
            FROM tenant_api_keys
          `);
          await connection.execute('DROP TABLE tenant_api_keys');
          await connection.execute('RENAME TABLE tenant_api_keys_new TO tenant_api_keys');
          await connection.execute('SET FOREIGN_KEY_CHECKS=1');
          logger.info('✅ tenant_api_keys migrated to new schema');
 
          const [recheckedApiKeyColumns] = await connection.query(`
            SELECT COLUMN_NAME 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
              AND TABLE_NAME = 'tenant_api_keys'
          `);
          existingTenantApiKeyColumns = recheckedApiKeyColumns.map(col => col.COLUMN_NAME);
        } catch (migrationError) {
          logger.warn('tenant_api_keys migration failed', { error: migrationError.message });
        }
      }
 
      if (!existingTenantApiKeyColumns.includes('key_prefix')) {
        try {
          await connection.execute(`ALTER TABLE tenant_api_keys ADD COLUMN key_prefix VARCHAR(20) NOT NULL AFTER key_name`);
          logger.info('✅ Added key_prefix to tenant_api_keys');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_api_keys key_prefix:', e.message); }
      }
      if (!existingTenantApiKeyColumns.includes('key_hash')) {
        try {
          await connection.execute(`ALTER TABLE tenant_api_keys ADD COLUMN key_hash CHAR(64) NOT NULL AFTER key_prefix`);
          logger.info('✅ Added key_hash to tenant_api_keys');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_api_keys key_hash:', e.message); }
      }
      if (!existingTenantApiKeyColumns.includes('is_active')) {
        try {
          await connection.execute(`ALTER TABLE tenant_api_keys ADD COLUMN is_active BOOLEAN DEFAULT TRUE AFTER key_hash`);
          logger.info('✅ Added is_active to tenant_api_keys');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_api_keys is_active:', e.message); }
      }
      if (!existingTenantApiKeyColumns.includes('last_used_at')) {
        try {
          await connection.execute(`ALTER TABLE tenant_api_keys ADD COLUMN last_used_at DATETIME AFTER is_active`);
          logger.info('✅ Added last_used_at to tenant_api_keys');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_api_keys last_used_at:', e.message); }
      }
      if (!existingTenantApiKeyColumns.includes('revoked_at')) {
        try {
          await connection.execute(`ALTER TABLE tenant_api_keys ADD COLUMN revoked_at DATETIME AFTER last_used_at`);
          logger.info('✅ Added revoked_at to tenant_api_keys');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_api_keys revoked_at:', e.message); }
      }
    } catch (e) {
      logger.warn('tenant_api_keys columns check failed', { error: e.message });
    }
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tenant_webhooks (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        event_type VARCHAR(100) NOT NULL,
        webhook_url VARCHAR(500) NOT NULL,
        secret_key VARCHAR(255),
        is_active BOOLEAN DEFAULT TRUE,
        last_triggered_at DATETIME,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_event_type (event_type),
        INDEX idx_is_active (is_active),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tenant_webhooks table created/verified');
    try {
      const [tenantWebhooksColumns] = await connection.query(`
        SELECT COLUMN_NAME 
        FROM information_schema.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'tenant_webhooks'
      `);
      let existingTenantWebhooksColumns = tenantWebhooksColumns.map(col => col.COLUMN_NAME);
 
      const hasLegacySchema = existingTenantWebhooksColumns.includes('events') ||
        existingTenantWebhooksColumns.includes('webhook_name') ||
        existingTenantWebhooksColumns.includes('status') ||
        existingTenantWebhooksColumns.includes('retry_count') ||
        existingTenantWebhooksColumns.includes('timeout_seconds');
 
      if (hasLegacySchema) {
        try {
          await connection.execute('SET FOREIGN_KEY_CHECKS=0');
          await connection.execute('DROP TABLE IF EXISTS tenant_webhooks_new');
          await connection.execute(`
            CREATE TABLE tenant_webhooks_new (
              id INT AUTO_INCREMENT PRIMARY KEY,
              tenant_id INT NOT NULL,
              event_type VARCHAR(100) NOT NULL DEFAULT 'message.received',
              webhook_url VARCHAR(500) NOT NULL,
              secret_key VARCHAR(255),
              is_active BOOLEAN DEFAULT TRUE,
              last_triggered_at DATETIME,
              created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
              updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              INDEX idx_tenant_id (tenant_id),
              INDEX idx_event_type (event_type),
              INDEX idx_is_active (is_active),
              FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
          `);
          await connection.execute(`
            INSERT INTO tenant_webhooks_new (id, tenant_id, event_type, webhook_url, secret_key, is_active, last_triggered_at, created_at, updated_at)
            SELECT id, tenant_id, event_type, webhook_url, secret_key, is_active, last_triggered_at, created_at, updated_at
            FROM tenant_webhooks
          `);
          await connection.execute('DROP TABLE tenant_webhooks');
          await connection.execute('RENAME TABLE tenant_webhooks_new TO tenant_webhooks');
          await connection.execute('SET FOREIGN_KEY_CHECKS=1');
          logger.info('✅ tenant_webhooks migrated to new schema');
 
          const [recheckedColumns] = await connection.query(`
            SELECT COLUMN_NAME 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
              AND TABLE_NAME = 'tenant_webhooks'
          `);
          existingTenantWebhooksColumns = recheckedColumns.map(col => col.COLUMN_NAME);
        } catch (migrationError) {
          logger.warn('tenant_webhooks migration failed', { error: migrationError.message });
        }
      }
 
      if (!existingTenantWebhooksColumns.includes('event_type')) {
        try {
          await connection.execute(`ALTER TABLE tenant_webhooks ADD COLUMN event_type VARCHAR(100) NOT NULL DEFAULT 'message.received' AFTER tenant_id`);
          logger.info('✅ Added event_type to tenant_webhooks');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_webhooks event_type:', e.message); }
      }
      if (!existingTenantWebhooksColumns.includes('webhook_url')) {
        try {
          await connection.execute(`ALTER TABLE tenant_webhooks ADD COLUMN webhook_url VARCHAR(500) NOT NULL AFTER event_type`);
          logger.info('✅ Added webhook_url to tenant_webhooks');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_webhooks webhook_url:', e.message); }
      }
      if (!existingTenantWebhooksColumns.includes('secret_key')) {
        try {
          await connection.execute(`ALTER TABLE tenant_webhooks ADD COLUMN secret_key VARCHAR(255) AFTER webhook_url`);
          logger.info('✅ Added secret_key to tenant_webhooks');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_webhooks secret_key:', e.message); }
      }
      if (!existingTenantWebhooksColumns.includes('is_active')) {
        try {
          await connection.execute(`ALTER TABLE tenant_webhooks ADD COLUMN is_active BOOLEAN DEFAULT TRUE AFTER secret_key`);
          logger.info('✅ Added is_active to tenant_webhooks');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_webhooks is_active:', e.message); }
      }
      if (!existingTenantWebhooksColumns.includes('last_triggered_at')) {
        try {
          await connection.execute(`ALTER TABLE tenant_webhooks ADD COLUMN last_triggered_at DATETIME AFTER is_active`);
          logger.info('✅ Added last_triggered_at to tenant_webhooks');
        } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('tenant_webhooks last_triggered_at:', e.message); }
      }
 
    } catch (e) {
      logger.warn('tenant_webhooks columns check failed', { error: e.message });
    }
 
    // ============================================
    // Plan Addons Tables
    // ============================================
 
    // Create plan_addons table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS plan_addons (
        id INT AUTO_INCREMENT PRIMARY KEY,
        resource_key VARCHAR(50) NOT NULL UNIQUE,
        resource_name VARCHAR(100) NOT NULL,
        description TEXT,
        unit_price DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
        currency VARCHAR(3) DEFAULT 'USD',
        stripe_price_id VARCHAR(255),
        paypal_plan_id VARCHAR(255),
        active BOOLEAN DEFAULT TRUE,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_resource_key (resource_key),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ plan_addons table created/verified');
 
    // Create addon_purchases table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS addon_purchases (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        items JSON NOT NULL,
        total_amount DECIMAL(10, 2) NOT NULL,
        currency VARCHAR(3) DEFAULT 'USD',
        status ENUM('pending', 'completed', 'failed', 'cancelled') DEFAULT 'pending',
        payment_method VARCHAR(50),
        payment_id VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_status (status),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ addon_purchases table created/verified');
 
    // Create tenant_addons table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tenant_addons (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        addon_id INT NOT NULL,
        quantity INT NOT NULL DEFAULT 1,
        status ENUM('active', 'cancelled', 'expired') DEFAULT 'active',
        started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        expires_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (addon_id) REFERENCES plan_addons(id) ON DELETE CASCADE,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_addon_id (addon_id),
        INDEX idx_status (status)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tenant_addons table created/verified');
 
    // Create system_addons table (for uploadable plugins/extensions)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS system_addons (
        id INT AUTO_INCREMENT PRIMARY KEY,
        slug VARCHAR(100) NOT NULL UNIQUE,
        name VARCHAR(255) NOT NULL,
        description TEXT,
        version VARCHAR(50) DEFAULT '1.0.0',
        author VARCHAR(255),
        icon VARCHAR(255) DEFAULT 'puzzle-piece',
        directory VARCHAR(255) NOT NULL,
        config JSON,
        active BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_slug (slug),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ system_addons table created/verified');
 
    // Check if addon directories exist before registering
    const fs = require('fs');
    const path = require('path');
    const addonsDir = path.join(__dirname, '..', 'addons');
 
    // Insert email-marketing addon if not exists (only if directory exists)
    const emailMarketingDir = path.join(addonsDir, 'email-marketing');
    const emailMarketingExists = fs.existsSync(emailMarketingDir);
    
    if (emailMarketingExists) {
      await connection.execute(`
        INSERT IGNORE INTO system_addons (slug, name, description, version, icon, directory, active)
        VALUES ('email-marketing', 'Email Marketing', 'Complete email marketing solution with IMAP/SMTP integration, templates, and campaigns', '1.0.0', 'envelope', 'email-marketing', FALSE)
      `);
      logger.info('✅ email-marketing addon registered (inactive by default)');
    } else {
      logger.info('⚠️ email-marketing addon directory not found, skipping registration');
    }
 
    // Insert biolink addon if not exists (only if directory exists)
    const biolinkDir = path.join(addonsDir, 'biolink');
    const biolinkExists = fs.existsSync(biolinkDir);
    
    if (biolinkExists) {
      await connection.execute(`
        INSERT IGNORE INTO system_addons (slug, name, description, version, icon, directory, active)
        VALUES ('biolink', 'Bio Link', 'Create beautiful bio link pages, short links, QR codes, file sharing, vcards, and more with drag & drop customization', '1.0.0', 'link', 'biolink', FALSE)
      `);
      logger.info('✅ biolink addon registered (inactive by default)');
      
      // Update biolink_events table with enhanced columns for robust event management
      try {
        // Check if biolink_events table exists
        const [tables] = await connection.query(`
          SELECT TABLE_NAME 
          FROM information_schema.TABLES 
          WHERE TABLE_SCHEMA = DATABASE() 
            AND TABLE_NAME = 'biolink_events'
        `);
        
        if (tables.length > 0) {
          // Get existing columns
          const [eventColumns] = await connection.query(`
            SELECT COLUMN_NAME 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
              AND TABLE_NAME = 'biolink_events'
          `);
          const existingEventColumns = eventColumns.map(col => col.COLUMN_NAME);
          
          // Add short_description column
          if (!existingEventColumns.includes('short_description')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN short_description TEXT AFTER description`);
            logger.info('✅ Added short_description column to biolink_events');
          }
          
          // Add long_description column
          if (!existingEventColumns.includes('long_description')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN long_description TEXT AFTER short_description`);
            logger.info('✅ Added long_description column to biolink_events');
          }
          
          // Add venue_name column
          if (!existingEventColumns.includes('venue_name')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN venue_name VARCHAR(255) AFTER location_url`);
            logger.info('✅ Added venue_name column to biolink_events');
          }
          
          // Add address column
          if (!existingEventColumns.includes('address')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN address VARCHAR(500) AFTER venue_name`);
            logger.info('✅ Added address column to biolink_events');
          }
          
          // Add latitude column
          if (!existingEventColumns.includes('latitude')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN latitude DECIMAL(10, 8) AFTER address`);
            logger.info('✅ Added latitude column to biolink_events');
          }
          
          // Add longitude column
          if (!existingEventColumns.includes('longitude')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN longitude DECIMAL(11, 8) AFTER latitude`);
            logger.info('✅ Added longitude column to biolink_events');
          }
          
          // Add venue_description column
          if (!existingEventColumns.includes('venue_description')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN venue_description TEXT AFTER longitude`);
            logger.info('✅ Added venue_description column to biolink_events');
          }
          
          // Add cover_image column
          if (!existingEventColumns.includes('cover_image')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN cover_image VARCHAR(500) AFTER venue_description`);
            logger.info('✅ Added cover_image column to biolink_events');
          }
          
          // Add gallery column (JSON array of image URLs)
          if (!existingEventColumns.includes('gallery')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN gallery JSON AFTER cover_image`);
            logger.info('✅ Added gallery column to biolink_events');
          }
          
          // Add tickets column (JSON array of ticket objects)
          if (!existingEventColumns.includes('tickets')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN tickets JSON AFTER gallery`);
            logger.info('✅ Added tickets column to biolink_events');
          }
          
          // Add rating column (age rating/classification)
          if (!existingEventColumns.includes('rating')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN rating VARCHAR(50) AFTER tickets`);
            logger.info('✅ Added rating column to biolink_events');
          }
          
          // Add customization columns
          if (!existingEventColumns.includes('bg_color')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN bg_color VARCHAR(20) DEFAULT '#1e293b' AFTER rating`);
            logger.info('✅ Added bg_color column to biolink_events');
          }
          
          if (!existingEventColumns.includes('card_bg_color')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN card_bg_color VARCHAR(20) DEFAULT '#ffffff' AFTER bg_color`);
            logger.info('✅ Added card_bg_color column to biolink_events');
          }
          
          if (!existingEventColumns.includes('text_color')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN text_color VARCHAR(20) DEFAULT '#1e293b' AFTER card_bg_color`);
            logger.info('✅ Added text_color column to biolink_events');
          }
          
          if (!existingEventColumns.includes('accent_color')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN accent_color VARCHAR(20) DEFAULT '#667eea' AFTER text_color`);
            logger.info('✅ Added accent_color column to biolink_events');
          }
          
          if (!existingEventColumns.includes('button_color')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN button_color VARCHAR(20) DEFAULT '#667eea' AFTER accent_color`);
            logger.info('✅ Added button_color column to biolink_events');
          }
          
          if (!existingEventColumns.includes('button_text_color')) {
            await connection.execute(`ALTER TABLE biolink_events ADD COLUMN button_text_color VARCHAR(20) DEFAULT '#ffffff' AFTER button_color`);
            logger.info('✅ Added button_text_color column to biolink_events');
          }
          
          logger.info('✅ biolink_events table enhanced with all event management columns');
        }
      } catch (error) {
        logger.warn('biolink_events table update:', error.message);
      }
    } else {
      logger.info('⚠️ biolink addon directory not found, skipping registration');
    }
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(100),
        email_address VARCHAR(255) NOT NULL,
        imap_host VARCHAR(255),
        imap_port INT,
        imap_secure BOOLEAN DEFAULT TRUE,
        imap_user VARCHAR(255),
        imap_password TEXT,
        imap_sent_folder VARCHAR(255) DEFAULT 'Sent',
        smtp_host VARCHAR(255),
        smtp_port INT,
        smtp_secure BOOLEAN DEFAULT TRUE,
        smtp_user VARCHAR(255),
        smtp_password TEXT,
        status ENUM('active', 'inactive') DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_email (email_address),
        INDEX idx_status (status)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_accounts table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_account_access (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NOT NULL,
        scope_type ENUM('store', 'department', 'user') NOT NULL,
        scope_id INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (account_id) REFERENCES email_accounts(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_account (account_id),
        INDEX idx_scope (scope_type, scope_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_account_access table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(255) NOT NULL,
        subject VARCHAR(255),
        html_content LONGTEXT,
        design_json LONGTEXT,
        created_by INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_name (name)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_templates table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NOT NULL,
        direction ENUM('sent', 'received') DEFAULT 'sent',
        subject VARCHAR(255),
        from_email VARCHAR(255),
        to_email TEXT,
        cc TEXT,
        bcc TEXT,
        html_content LONGTEXT,
        text_content LONGTEXT,
        message_id VARCHAR(255),
        status ENUM('sent', 'failed') DEFAULT 'sent',
        error_message TEXT,
        sent_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (account_id) REFERENCES email_accounts(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_account (account_id),
        INDEX idx_direction (direction),
        INDEX idx_sent_at (sent_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_messages table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_campaigns (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NOT NULL,
        template_id INT NULL,
        name VARCHAR(255) NOT NULL,
        subject VARCHAR(255),
        from_name VARCHAR(255),
        from_email VARCHAR(255),
        schedule_at TIMESTAMP NULL,
        status ENUM('scheduled', 'sending', 'completed', 'failed', 'cancelled') DEFAULT 'scheduled',
        total_recipients INT DEFAULT 0,
        sent_count INT DEFAULT 0,
        failed_count INT DEFAULT 0,
        error_message TEXT,
        created_by INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (account_id) REFERENCES email_accounts(id) ON DELETE CASCADE,
        FOREIGN KEY (template_id) REFERENCES email_templates(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_schedule (schedule_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_campaigns table created/verified');
 
    // Add error_message column if not exists
    try {
      await connection.execute(`
        ALTER TABLE email_campaigns 
        ADD COLUMN IF NOT EXISTS error_message TEXT AFTER failed_count
      `);
    } catch (e) {
      // Column might already exist
    }
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_campaign_recipients (
        id INT AUTO_INCREMENT PRIMARY KEY,
        campaign_id INT NOT NULL,
        email_address VARCHAR(255) NOT NULL,
        status ENUM('pending', 'sent', 'failed') DEFAULT 'pending',
        sent_at TIMESTAMP NULL,
        error_message TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (campaign_id) REFERENCES email_campaigns(id) ON DELETE CASCADE,
        INDEX idx_campaign (campaign_id),
        INDEX idx_status (status)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_campaign_recipients table created/verified');
 
    // Create email_contact_groups table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_contact_groups (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(255) NOT NULL,
        description TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        UNIQUE KEY unique_tenant_group_name (tenant_id, name)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_contact_groups table created/verified');
 
    // Create email_contacts table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_contacts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        group_id INT DEFAULT NULL,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL,
        source_contact_id INT DEFAULT NULL COMMENT 'Reference to main contacts table',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (group_id) REFERENCES email_contact_groups(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_group (group_id),
        INDEX idx_email (email),
        INDEX idx_source_contact (source_contact_id),
        UNIQUE KEY unique_tenant_email (tenant_id, email)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_contacts table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS omnichannel_accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        channel ENUM('instagram', 'messenger', 'telegram') NOT NULL,
        display_name VARCHAR(255),
        external_id VARCHAR(255),
        access_token TEXT,
        metadata JSON,
        status ENUM('active', 'inactive') DEFAULT 'active',
        created_by INT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_channel (channel),
        INDEX idx_status (status)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ omnichannel_accounts table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS omnichannel_conversations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NOT NULL,
        channel ENUM('instagram', 'messenger', 'telegram') NOT NULL,
        external_thread_id VARCHAR(255),
        contact_name VARCHAR(255),
        contact_handle VARCHAR(255),
        status ENUM('open', 'closed', 'pending') DEFAULT 'open',
        last_message_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (account_id) REFERENCES omnichannel_accounts(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_account (account_id),
        INDEX idx_channel (channel),
        INDEX idx_status (status),
        INDEX idx_last_message (last_message_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ omnichannel_conversations table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS omnichannel_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        conversation_id INT NOT NULL,
        direction ENUM('in', 'out') DEFAULT 'out',
        message_type VARCHAR(50) DEFAULT 'text',
        body TEXT,
        metadata JSON,
        external_message_id VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (conversation_id) REFERENCES omnichannel_conversations(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_conversation (conversation_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ omnichannel_messages table created/verified');
 
    // Add recipient_groups column to email_campaigns if not exists
    const [campaignColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'email_campaigns'
    `);
    const existingCampaignColumns = campaignColumns.map(col => col.COLUMN_NAME);
    
    if (!existingCampaignColumns.includes('recipient_groups')) {
      try {
        await connection.execute(`
          ALTER TABLE email_campaigns 
          ADD COLUMN recipient_groups TEXT COMMENT 'JSON array of group IDs' AFTER from_email
        `);
        logger.info('✅ Added recipient_groups column to email_campaigns table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('recipient_groups column:', e.message);
        }
      }
    }
 
    // Insert default add-ons
    const defaultAddons = [
      ['stores', 'Store', 'Additional store location', 0.50, 'USD', 1],
      ['departments', 'Department', 'Additional department', 0.50, 'USD', 2],
      ['users', 'User', 'Additional user account', 0.70, 'USD', 3],
      ['conversations', 'Conversations', '100 additional conversations', 2.00, 'USD', 4],
      ['messages', 'Messages', '1000 additional messages', 5.00, 'USD', 5],
      ['contacts', 'Contacts', '100 additional contacts', 1.00, 'USD', 6],
      ['faq', 'FAQ', 'Additional FAQ entries for automated responses', 1.00, 'USD', 7],
      ['widget', 'Chat Widget', 'Customizable chat widget for your website', 2.50, 'USD', 8],
      ['invoice', 'Invoice', 'Invoice and quote generation feature', 3.00, 'USD', 9],
      ['ai', 'AI Assistant', 'AI-powered automated responses', 10.00, 'USD', 10],
      ['woocommerce', 'WooCommerce', 'WooCommerce integration for e-commerce', 5.00, 'USD', 11],
      ['payment_links', 'Payment Links', 'Generate payment links for customers', 3.00, 'USD', 12],
      ['email_accounts', 'Email Accounts', 'Additional email accounts for marketing and inbox', 4.00, 'USD', 13],
      ['email_sends', 'Email Sends', 'Additional monthly email sends', 5.00, 'USD', 14],
      ['omnichannel_accounts', 'Omnichannel Accounts', 'Additional omnichannel account connections', 6.00, 'USD', 15]
    ];
 
    for (const [key, name, desc, price, currency, order] of defaultAddons) {
      await connection.execute(`
        INSERT IGNORE INTO plan_addons (resource_key, resource_name, description, unit_price, currency, sort_order)
        VALUES (?, ?, ?, ?, ?, ?)
      `, [key, name, desc, price, currency, order]);
    }
    logger.info('✅ Default plan addons created/verified');
 
    // ============================================
    // Bio Link Tables
    // ============================================
 
    // Create biolink_projects table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS biolink_projects (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        user_id INT,
        name VARCHAR(255) NOT NULL,
        slug VARCHAR(100) NOT NULL,
        type ENUM('biopage', 'shortlink', 'qrcode', 'file', 'vcard', 'event', 'html') DEFAULT 'biopage',
        status ENUM('active', 'draft', 'inactive') DEFAULT 'draft',
        destination_url TEXT,
        clicks INT DEFAULT 0,
        settings JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_slug (slug),
        INDEX idx_tenant (tenant_id),
        INDEX idx_type (type),
        INDEX idx_status (status)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ biolink_projects table created/verified');
 
    const [biolinkProjectsColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'biolink_projects'
    `);
    const existingBiolinkProjectsColumns = biolinkProjectsColumns.map(col => col.COLUMN_NAME);
 
    if (!existingBiolinkProjectsColumns.includes('destination_url')) {
      try {
        await connection.execute(`ALTER TABLE biolink_projects ADD COLUMN destination_url TEXT AFTER status`);
        logger.info('✅ Added destination_url to biolink_projects');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_projects destination_url:', e.message); }
    }
 
    if (!existingBiolinkProjectsColumns.includes('settings')) {
      try {
        await connection.execute(`ALTER TABLE biolink_projects ADD COLUMN settings JSON AFTER clicks`);
        logger.info('✅ Added settings to biolink_projects');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_projects settings:', e.message); }
    }
 
    // Add download tracking columns for file transfer
    if (!existingBiolinkProjectsColumns.includes('download_count')) {
      try {
        await connection.execute(`ALTER TABLE biolink_projects ADD COLUMN download_count INT DEFAULT 0 AFTER clicks`);
        logger.info('✅ Added download_count to biolink_projects');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_projects download_count:', e.message); }
    }
 
    if (!existingBiolinkProjectsColumns.includes('max_downloads')) {
      try {
        await connection.execute(`ALTER TABLE biolink_projects ADD COLUMN max_downloads INT DEFAULT 0 AFTER download_count`);
        logger.info('✅ Added max_downloads to biolink_projects');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_projects max_downloads:', e.message); }
    }
 
    if (!existingBiolinkProjectsColumns.includes('download_expiration')) {
      try {
        await connection.execute(`ALTER TABLE biolink_projects ADD COLUMN download_expiration TIMESTAMP NULL AFTER max_downloads`);
        logger.info('✅ Added download_expiration to biolink_projects');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_projects download_expiration:', e.message); }
    }
 
    if (!existingBiolinkProjectsColumns.includes('password')) {
      try {
        await connection.execute(`ALTER TABLE biolink_projects ADD COLUMN password VARCHAR(255) NULL AFTER download_expiration`);
        logger.info('✅ Added password to biolink_projects');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_projects password:', e.message); }
    }
 
    // Create biolink_pages table (for biopage type projects)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS biolink_pages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        project_id INT NOT NULL,
        title VARCHAR(255),
        description TEXT,
        avatar_url VARCHAR(500),
        background_type ENUM('color', 'gradient', 'image') DEFAULT 'color',
        background_value VARCHAR(500) DEFAULT '#ffffff',
        text_color VARCHAR(20) DEFAULT '#000000',
        font_family VARCHAR(100) DEFAULT 'Inter',
        button_style VARCHAR(50) DEFAULT 'rounded',
        button_color VARCHAR(20) DEFAULT '#000000',
        button_text_color VARCHAR(20) DEFAULT '#ffffff',
        seo_title VARCHAR(255),
        seo_description TEXT,
        seo_image VARCHAR(500),
        favicon VARCHAR(500),
        password VARCHAR(255),
        sensitive_content BOOLEAN DEFAULT FALSE,
        leap_link VARCHAR(500),
        analytics_code TEXT,
        custom_css TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_project (project_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ biolink_pages table created/verified');
 
    // Create biolink_blocks table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS biolink_blocks (
        id INT AUTO_INCREMENT PRIMARY KEY,
        page_id INT NOT NULL,
        type VARCHAR(50) NOT NULL,
        title VARCHAR(255),
        content JSON,
        settings JSON,
        sort_order INT DEFAULT 0,
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_page (page_id),
        INDEX idx_sort (sort_order)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ biolink_blocks table created/verified');
 
    // Create biolink_analytics table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS biolink_analytics (
        id INT AUTO_INCREMENT PRIMARY KEY,
        project_id INT NOT NULL,
        block_id INT,
        event_type ENUM('view', 'click', 'download') DEFAULT 'view',
        ip_address VARCHAR(45),
        user_agent TEXT,
        referrer VARCHAR(500),
        country VARCHAR(100),
        city VARCHAR(100),
        device_type VARCHAR(50),
        browser VARCHAR(100),
        os VARCHAR(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_project (project_id),
        INDEX idx_block (block_id),
        INDEX idx_event (event_type),
        INDEX idx_created (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ biolink_analytics table created/verified');
 
    // Add missing columns to biolink tables
    // Add tenant_id to biolink_pages if missing
    const [biolinkPagesColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'biolink_pages'
    `);
    const existingBiolinkPagesColumns = biolinkPagesColumns.map(col => col.COLUMN_NAME);
 
    if (!existingBiolinkPagesColumns.includes('tenant_id')) {
      try {
        await connection.execute(`ALTER TABLE biolink_pages ADD COLUMN tenant_id INT NOT NULL DEFAULT 0 AFTER project_id`);
        logger.info('✅ Added tenant_id to biolink_pages');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_pages tenant_id:', e.message); }
    }
 
    // Add tenant_id to biolink_blocks if missing
    const [biolinkBlocksColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'biolink_blocks'
    `);
    const existingBiolinkBlocksColumns = biolinkBlocksColumns.map(col => col.COLUMN_NAME);
 
    if (!existingBiolinkBlocksColumns.includes('tenant_id')) {
      try {
        await connection.execute(`ALTER TABLE biolink_blocks ADD COLUMN tenant_id INT NOT NULL DEFAULT 0 AFTER page_id`);
        logger.info('✅ Added tenant_id to biolink_blocks');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_blocks tenant_id:', e.message); }
    }
 
    // Add position column to biolink_blocks if missing (alias for sort_order)
    if (!existingBiolinkBlocksColumns.includes('position')) {
      try {
        await connection.execute(`ALTER TABLE biolink_blocks ADD COLUMN position INT DEFAULT 0 AFTER settings`);
        logger.info('✅ Added position to biolink_blocks');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_blocks position:', e.message); }
    }
 
    // Add tenant_id to biolink_analytics if missing
    const [biolinkAnalyticsColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'biolink_analytics'
    `);
    const existingBiolinkAnalyticsColumns = biolinkAnalyticsColumns.map(col => col.COLUMN_NAME);
 
    if (!existingBiolinkAnalyticsColumns.includes('tenant_id')) {
      try {
        await connection.execute(`ALTER TABLE biolink_analytics ADD COLUMN tenant_id INT NOT NULL DEFAULT 0 AFTER id`);
        logger.info('✅ Added tenant_id to biolink_analytics');
      } catch (e) { if (e.code !== 'ER_DUP_FIELDNAME') logger.warn('biolink_analytics tenant_id:', e.message); }
    }
 
    // Create biolink_leads table for form submissions
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS biolink_leads (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        project_id INT NOT NULL,
        block_id INT NOT NULL,
        lead_type ENUM('email', 'phone', 'contact') NOT NULL,
        email VARCHAR(255),
        phone VARCHAR(50),
        name VARCHAR(255),
        message TEXT,
        ip_address VARCHAR(45),
        user_agent TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_project (project_id),
        INDEX idx_block (block_id),
        INDEX idx_type (lead_type),
        INDEX idx_created (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ biolink_leads table created/verified');
 
    // ============================================
    // Notification System Tables
    // ============================================
 
    // Create email_notification_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_notification_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        smtp_host VARCHAR(255),
        smtp_port INT DEFAULT 587,
        smtp_secure BOOLEAN DEFAULT FALSE,
        smtp_user VARCHAR(255),
        smtp_password VARCHAR(255),
        from_email VARCHAR(255),
        from_name VARCHAR(255) DEFAULT 'Misayan SaaS',
        enabled BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_notification_settings table created/verified');
 
    // Create whatsapp_notification_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_notification_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        phone_number VARCHAR(20),
        session_name VARCHAR(100) DEFAULT 'superadmin_notifications',
        enabled BOOLEAN DEFAULT FALSE,
        connected BOOLEAN DEFAULT FALSE,
        qr_code TEXT,
        last_connected_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_notification_settings table created/verified');
 
    // Create email_notification_templates table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS email_notification_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        template_key VARCHAR(100) UNIQUE NOT NULL,
        template_name VARCHAR(255) NOT NULL,
        category ENUM('tenant', 'subscription', 'security', 'system') NOT NULL,
        subject VARCHAR(500) NOT NULL,
        body TEXT NOT NULL,
        html_body TEXT,
        variables JSON,
        enabled BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_category (category),
        INDEX idx_template_key (template_key),
        INDEX idx_enabled (enabled)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ email_notification_templates table created/verified');
 
    // Create whatsapp_notification_templates table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_notification_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        template_key VARCHAR(100) UNIQUE NOT NULL,
        template_name VARCHAR(255) NOT NULL,
        category ENUM('tenant', 'subscription', 'security', 'system') NOT NULL,
        message TEXT NOT NULL,
        variables JSON,
        enabled BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_category (category),
        INDEX idx_template_key (template_key),
        INDEX idx_enabled (enabled)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_notification_templates table created/verified');
 
    // Create plan_expiration_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS plan_expiration_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        days_before_1 INT DEFAULT 7,
        days_before_2 INT DEFAULT 3,
        days_before_3 INT DEFAULT 1,
        days_before_4 INT DEFAULT 0,
        days_after_1 INT DEFAULT 1,
        days_after_2 INT DEFAULT 3,
        days_after_3 INT DEFAULT 7,
        enabled BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ plan_expiration_settings table created/verified');
 
    // Create notification_logs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS notification_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        notification_type ENUM('email', 'whatsapp') NOT NULL,
        template_key VARCHAR(100),
        recipient VARCHAR(255) NOT NULL,
        subject VARCHAR(500),
        message TEXT,
        status ENUM('pending', 'sent', 'failed') DEFAULT 'pending',
        error_message TEXT,
        metadata JSON,
        sent_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_type (notification_type),
        INDEX idx_status (status),
        INDEX idx_created_at (created_at),
        INDEX idx_template_key (template_key)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ notification_logs table created/verified');
 
    // Create scheduled_notifications table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS scheduled_notifications (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        notification_type ENUM('email', 'whatsapp') NOT NULL,
        template_key VARCHAR(100) NOT NULL,
        scheduled_date DATE NOT NULL,
        scheduled_time TIME DEFAULT '09:00:00',
        status ENUM('pending', 'sent', 'cancelled', 'failed') DEFAULT 'pending',
        sent_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_scheduled_date (scheduled_date),
        INDEX idx_status (status)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ scheduled_notifications table created/verified');
 
    // Insert default notification settings
    await connection.execute(`INSERT IGNORE INTO email_notification_settings (id, enabled) VALUES (1, FALSE)`);
    await connection.execute(`INSERT IGNORE INTO whatsapp_notification_settings (id, enabled) VALUES (1, FALSE)`);
    await connection.execute(`INSERT IGNORE INTO plan_expiration_settings (id) VALUES (1)`);
    logger.info('✅ Default notification settings created/verified');
 
    // ============================================
    // WhatsApp Cloud API Tables
    // ============================================
 
    // Create whatsapp_cloud_accounts table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_name VARCHAR(255) NOT NULL,
        waba_id VARCHAR(255),
        phone_number_id VARCHAR(255) NOT NULL,
        phone_number VARCHAR(20),
        access_token TEXT,
        app_id VARCHAR(255),
        app_secret VARCHAR(255),
        status ENUM('connected', 'disconnected', 'error') DEFAULT 'connected',
        is_default BOOLEAN DEFAULT FALSE,
        webhook_verified BOOLEAN DEFAULT FALSE,
        verify_token VARCHAR(255) NULL,
        templates_synced_at TIMESTAMP NULL,
        templates_count INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_phone_number_id (phone_number_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_is_default (is_default)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_accounts table created/verified');
 
    // Add verify_token column if it doesn't exist (migration for existing installations)
    try {
      const [columns] = await connection.execute(
        'SHOW COLUMNS FROM whatsapp_cloud_accounts LIKE ?',
        ['verify_token']
      );
      
      if (columns.length === 0) {
        await connection.execute(
          'ALTER TABLE whatsapp_cloud_accounts ADD COLUMN verify_token VARCHAR(255) NULL AFTER webhook_verified'
        );
        logger.info('✅ verify_token column added to whatsapp_cloud_accounts table');
      }
    } catch (error) {
      logger.warn('Could not add verify_token column (may already exist)', { error: error.message });
    }
 
    // Create whatsapp_cloud_templates table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_templates (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NOT NULL,
        template_id VARCHAR(255) NOT NULL,
        name VARCHAR(255) NOT NULL,
        language VARCHAR(10) NOT NULL,
        status VARCHAR(50) NOT NULL,
        category VARCHAR(50) NOT NULL,
        components JSON,
        body TEXT,
        header TEXT,
        footer TEXT,
        buttons JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_template (account_id, template_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (account_id) REFERENCES whatsapp_cloud_accounts(id) ON DELETE CASCADE,
        INDEX idx_tenant_account (tenant_id, account_id),
        INDEX idx_status (status)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_templates table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_campaigns (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NOT NULL,
        template_id VARCHAR(255) NOT NULL,
        template_name VARCHAR(255) NOT NULL,
        source VARCHAR(50) DEFAULT 'meta',
        audience_type ENUM('all', 'groups', 'custom') DEFAULT 'all',
        audience_groups JSON,
        audience_custom_numbers JSON,
        filters JSON,
        schedule_at DATETIME NOT NULL,
        timezone VARCHAR(100) DEFAULT 'UTC',
        status ENUM('scheduled', 'sending', 'sent', 'cancelled', 'failed') DEFAULT 'scheduled',
        total_count INT DEFAULT 0,
        sent_count INT DEFAULT 0,
        failed_count INT DEFAULT 0,
        error_message TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (account_id) REFERENCES whatsapp_cloud_accounts(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_account (account_id),
        INDEX idx_status (status),
        INDEX idx_schedule_at (schedule_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_campaigns table created/verified');
 
    // Create whatsapp_cloud_conversations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_conversations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NOT NULL,
        contact_phone VARCHAR(20) NOT NULL,
        contact_name VARCHAR(255),
        contact_profile_pic VARCHAR(500),
        last_message_text TEXT,
        last_message_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        last_message_from ENUM('customer', 'business') DEFAULT 'customer',
        unread_count INT DEFAULT 0,
        status ENUM('open', 'pending', 'closed') DEFAULT 'open',
        assigned_to_user_id INT,
        claimed_by_user_id INT NULL,
        claimed_at TIMESTAMP NULL,
        department_id INT NULL,
        store_id INT NULL,
        source ENUM('whatsapp_cloud', 'whatsapp_web') DEFAULT 'whatsapp_cloud',
        original_conversation_id INT NULL,
        tags JSON NULL,
        notes TEXT NULL,
        priority ENUM('low', 'normal', 'high', 'urgent') DEFAULT 'normal',
        pipeline_stage VARCHAR(50) DEFAULT 'unassigned',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_conversation (account_id, contact_phone),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (account_id) REFERENCES whatsapp_cloud_accounts(id) ON DELETE CASCADE,
        INDEX idx_tenant_account (tenant_id, account_id),
        INDEX idx_contact_phone (contact_phone),
        INDEX idx_last_message_time (last_message_time),
        INDEX idx_status (status),
        INDEX idx_claimed_by (claimed_by_user_id),
        INDEX idx_department (department_id),
        INDEX idx_store (store_id),
        INDEX idx_source (source),
        INDEX idx_priority (priority),
        INDEX idx_pipeline_stage (pipeline_stage)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_conversations table created/verified');
 
    const [cloudConversationColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_cloud_conversations'
    `);
    const existingCloudConversationColumns = cloudConversationColumns.map(col => col.COLUMN_NAME);
 
    if (!existingCloudConversationColumns.includes('pipeline_stage')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_conversations ADD COLUMN pipeline_stage VARCHAR(50) DEFAULT 'unassigned'`);
        logger.info('✅ Added pipeline_stage column to whatsapp_cloud_conversations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('pipeline_stage column:', e.message);
        }
      }
    }
 
    if (!existingCloudConversationColumns.includes('stage_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_conversations ADD COLUMN stage_id VARCHAR(50) DEFAULT 'unassigned'`);
        logger.info('✅ Added stage_id column to whatsapp_cloud_conversations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('stage_id column:', e.message);
        }
      }
    }
 
    if (!existingCloudConversationColumns.includes('transferred_to_store')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_conversations ADD COLUMN transferred_to_store INT NULL`);
        logger.info('✅ Added transferred_to_store column to whatsapp_cloud_conversations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('transferred_to_store column:', e.message);
        }
      }
    }
 
    if (!existingCloudConversationColumns.includes('transferred_to_department')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_conversations ADD COLUMN transferred_to_department INT NULL`);
        logger.info('✅ Added transferred_to_department column to whatsapp_cloud_conversations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('transferred_to_department column:', e.message);
        }
      }
    }
 
    if (!existingCloudConversationColumns.includes('transferred_at')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_conversations ADD COLUMN transferred_at TIMESTAMP NULL`);
        logger.info('✅ Added transferred_at column to whatsapp_cloud_conversations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('transferred_at column:', e.message);
        }
      }
    }
 
    if (!existingCloudConversationColumns.includes('transferred_by_user_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_conversations ADD COLUMN transferred_by_user_id INT NULL`);
        logger.info('✅ Added transferred_by_user_id column to whatsapp_cloud_conversations');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('transferred_by_user_id column:', e.message);
        }
      }
    }
 
    // Create whatsapp_cloud_messages table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        conversation_id INT NOT NULL,
        message_id VARCHAR(255) NOT NULL UNIQUE,
        direction ENUM('inbound', 'outbound') NOT NULL,
        message_type ENUM('text', 'image', 'video', 'audio', 'document', 'location', 'sticker', 'template') DEFAULT 'text',
        text_content TEXT,
        media_url VARCHAR(500),
        caption TEXT,
        filename VARCHAR(255),
        status ENUM('sent', 'delivered', 'read', 'failed') DEFAULT 'sent',
        timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        sent_by_user_id INT NULL,
        is_internal_note BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (conversation_id) REFERENCES whatsapp_cloud_conversations(id) ON DELETE CASCADE,
        INDEX idx_conversation (conversation_id),
        INDEX idx_message_id (message_id),
        INDEX idx_timestamp (timestamp),
        INDEX idx_direction (direction),
        INDEX idx_status (status),
        INDEX idx_is_internal_note (is_internal_note)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_messages table created/verified');
 
    // Insert default email notification templates with complete HTML
    const emailTemplates = [
      {
        key: 'welcome',
        name: 'Welcome Email',
        category: 'tenant',
        subject: 'Welcome to {{platform_name}}!',
        body: 'Hello {{tenant_name}},\n\nWelcome to {{platform_name}}! Your account has been created successfully.\n\nYour subdomain: {{subdomain}}\nYour plan: {{plan_name}}\nTrial period: {{trial_days}} days\n\nGet started by logging in at: {{login_url}}\n\nBest regards,\n{{platform_name}} Team',
        html_body: `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #00a149 0%, #319131 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
<h1 style="color: white; margin: 0;">Welcome to {{platform_name}}!</h1>
</div>
<div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
<p>Hello <strong>{{tenant_name}}</strong>,</p>
<p>Your account has been created successfully! We're excited to have you on board.</p>
<div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
<h3 style="margin-top: 0; color: #00a149;">Your Account Details:</h3>
<ul style="list-style: none; padding: 0;">
<li style="padding: 8px 0; border-bottom: 1px solid #eee;"><strong>Subdomain:</strong> {{subdomain}}</li>
<li style="padding: 8px 0; border-bottom: 1px solid #eee;"><strong>Plan:</strong> {{plan_name}}</li>
<li style="padding: 8px 0;"><strong>Trial Period:</strong> {{trial_days}} days</li>
</ul>
</div>
<div style="text-align: center; margin: 30px 0;">
<a href="{{login_url}}" style="background: linear-gradient(135deg, #00a149 0%, #319131 100%); color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Login to Your Account</a>
</div>
<p>If you have any questions, feel free to contact us at <a href="mailto:{{support_email}}">{{support_email}}</a></p>
<p>Best regards,<br><strong>{{platform_name}} Team</strong></p>
</div>
</body>
</html>`,
        variables: '["tenant_name", "platform_name", "subdomain", "plan_name", "login_url", "trial_days", "support_email"]'
      },
      {
        key: 'password_reset',
        name: 'Password Reset',
        category: 'security',
        subject: 'Reset Your Password - {{platform_name}}',
        body: 'Hello {{tenant_name}},\n\nYou requested a password reset. Click the link below to reset your password:\n\n{{reset_link}}\n\nThis link expires in {{expiry_hours}} hour(s).\n\nIf you did not request this, please ignore this email.\n\nBest regards,\n{{platform_name}} Team',
        html_body: `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #00a149 0%, #319131 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
<h1 style="color: white; margin: 0;">Password Reset Request</h1>
</div>
<div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
<p>Hello <strong>{{tenant_name}}</strong>,</p>
<p>We received a request to reset your password. Click the button below to create a new password:</p>
<div style="text-align: center; margin: 30px 0;">
<a href="{{reset_link}}" style="background: linear-gradient(135deg, #00a149 0%, #319131 100%); color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Reset Password</a>
</div>
<div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107; margin: 20px 0;">
<p style="margin: 0;"><strong>⏰ Important:</strong> This link expires in <strong>{{expiry_hours}} hour(s)</strong>.</p>
</div>
<p style="color: #666; font-size: 14px;">If you didn't request this password reset, you can safely ignore this email. Your password will remain unchanged.</p>
<p>Best regards,<br><strong>{{platform_name}} Team</strong></p>
</div>
</body>
</html>`,
        variables: '["tenant_name", "platform_name", "reset_link", "expiry_hours", "support_email"]'
      },
      {
        key: 'payment_confirmation',
        name: 'Payment Confirmation',
        category: 'subscription',
        subject: 'Payment Confirmed - {{platform_name}}',
        body: 'Hello {{tenant_name}},\n\nYour payment has been confirmed!\n\nPlan: {{plan_name}}\nAmount: {{amount}}\nPayment Date: {{payment_date}}\nNext Billing Date: {{next_billing_date}}\n\nThank you for your business!\n\nBest regards,\n{{platform_name}} Team',
        html_body: `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
<h1 style="color: white; margin: 0;">✅ Payment Confirmed!</h1>
</div>
<div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
<p>Hello <strong>{{tenant_name}}</strong>,</p>
<p>Thank you! Your payment has been successfully processed.</p>
<div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
<h3 style="margin-top: 0; color: #28a745;">Payment Details:</h3>
<ul style="list-style: none; padding: 0;">
<li style="padding: 8px 0; border-bottom: 1px solid #eee;"><strong>Plan:</strong> {{plan_name}}</li>
<li style="padding: 8px 0; border-bottom: 1px solid #eee;"><strong>Amount:</strong> {{amount}}</li>
<li style="padding: 8px 0; border-bottom: 1px solid #eee;"><strong>Payment Date:</strong> {{payment_date}}</li>
<li style="padding: 8px 0;"><strong>Next Billing Date:</strong> {{next_billing_date}}</li>
</ul>
</div>
<p>Thank you for your continued trust in our services!</p>
<p>Best regards,<br><strong>{{platform_name}} Team</strong></p>
</div>
</body>
</html>`,
        variables: '["tenant_name", "platform_name", "plan_name", "amount", "payment_date", "next_billing_date"]'
      },
      {
        key: 'plan_expiring_soon',
        name: 'Plan Expiring Soon',
        category: 'subscription',
        subject: 'Your Plan Expires in {{days_remaining}} Days - {{platform_name}}',
        body: 'Hello {{tenant_name}},\n\nYour {{plan_name}} plan will expire in {{days_remaining}} days on {{expiry_date}}.\n\nTo avoid service interruption, please renew your subscription.\n\nRenew now: {{renewal_link}}\n\nBest regards,\n{{platform_name}} Team',
        html_body: `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
<h1 style="color: white; margin: 0;">⚠️ Plan Expiring Soon</h1>
</div>
<div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
<p>Hello <strong>{{tenant_name}}</strong>,</p>
<p>Your <strong>{{plan_name}}</strong> plan will expire in <strong>{{days_remaining}} days</strong>.</p>
<div style="background: #fff3cd; padding: 20px; border-radius: 8px; margin: 20px 0; text-align: center;">
<p style="margin: 0; font-size: 18px;"><strong>Expiration Date: {{expiry_date}}</strong></p>
</div>
<p>To avoid any service interruption, please renew your subscription before the expiration date.</p>
<div style="text-align: center; margin: 30px 0;">
<a href="{{renewal_link}}" style="background: linear-gradient(135deg, #00a149 0%, #319131 100%); color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Renew Now</a>
</div>
<p>Best regards,<br><strong>{{platform_name}} Team</strong></p>
</div>
</body>
</html>`,
        variables: '["tenant_name", "platform_name", "plan_name", "days_remaining", "expiry_date", "renewal_link"]'
      },
      {
        key: 'plan_expired',
        name: 'Plan Expired',
        category: 'subscription',
        subject: 'Your Plan Has Expired - {{platform_name}}',
        body: 'Hello {{tenant_name}},\n\nYour {{plan_name}} plan has expired on {{expiry_date}}.\n\nYou have {{grace_days}} days of grace period to renew your subscription before your account is suspended.\n\nRenew now: {{renewal_link}}\n\nBest regards,\n{{platform_name}} Team',
        html_body: `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #dc3545 0%, #c82333 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
<h1 style="color: white; margin: 0;">🚨 Plan Expired</h1>
</div>
<div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
<p>Hello <strong>{{tenant_name}}</strong>,</p>
<p>Your <strong>{{plan_name}}</strong> plan has expired on <strong>{{expiry_date}}</strong>.</p>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #dc3545;">
<p style="margin: 0;"><strong>⏰ Grace Period:</strong> You have <strong>{{grace_days}} days</strong> to renew your subscription before your account is suspended.</p>
</div>
<p>Please renew your subscription to continue using our services without interruption.</p>
<div style="text-align: center; margin: 30px 0;">
<a href="{{renewal_link}}" style="background: linear-gradient(135deg, #00a149 0%, #319131 100%); color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Renew Now</a>
</div>
<p>Best regards,<br><strong>{{platform_name}} Team</strong></p>
</div>
</body>
</html>`,
        variables: '["tenant_name", "platform_name", "plan_name", "expiry_date", "renewal_link", "grace_days"]'
      },
      {
        key: 'account_suspended',
        name: 'Account Suspended',
        category: 'system',
        subject: 'Account Suspended - {{platform_name}}',
        body: 'Hello {{tenant_name}},\n\nYour account has been suspended.\n\nReason: {{suspension_reason}}\n\nTo reactivate your account, please contact us at {{support_email}}.\n\nBest regards,\n{{platform_name}} Team',
        html_body: `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
<h1 style="color: white; margin: 0;">🔴 Account Suspended</h1>
</div>
<div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
<p>Hello <strong>{{tenant_name}}</strong>,</p>
<p>We regret to inform you that your account has been suspended.</p>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #dc3545;">
<p style="margin: 0;"><strong>Reason:</strong> {{suspension_reason}}</p>
</div>
<p>To reactivate your account, please contact our support team:</p>
<p style="text-align: center;"><a href="mailto:{{support_email}}" style="color: #00a149; font-weight: bold;">{{support_email}}</a></p>
<p>Best regards,<br><strong>{{platform_name}} Team</strong></p>
</div>
</body>
</html>`,
        variables: '["tenant_name", "platform_name", "suspension_reason", "support_email"]'
      },
      {
        key: 'account_reactivated',
        name: 'Account Reactivated',
        category: 'system',
        subject: 'Account Reactivated - {{platform_name}}',
        body: 'Hello {{tenant_name}},\n\nGreat news! Your account has been reactivated.\n\nYour plan: {{plan_name}}\n\nYou can now login at: {{login_url}}\n\nBest regards,\n{{platform_name}} Team',
        html_body: `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<div style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
<h1 style="color: white; margin: 0;">🟢 Account Reactivated!</h1>
</div>
<div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
<p>Hello <strong>{{tenant_name}}</strong>,</p>
<p>Great news! Your account has been successfully reactivated.</p>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #28a745;">
<p style="margin: 0;"><strong>Your Plan:</strong> {{plan_name}}</p>
</div>
<p>You can now access all features of your account.</p>
<div style="text-align: center; margin: 30px 0;">
<a href="{{login_url}}" style="background: linear-gradient(135deg, #00a149 0%, #319131 100%); color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Login Now</a>
</div>
<p>Thank you for your continued trust!</p>
<p>Best regards,<br><strong>{{platform_name}} Team</strong></p>
</div>
</body>
</html>`,
        variables: '["tenant_name", "platform_name", "plan_name", "login_url"]'
      }
    ];
 
    for (const template of emailTemplates) {
      await connection.execute(`
        INSERT INTO email_notification_templates (template_key, template_name, category, subject, body, html_body, variables)
        VALUES (?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
          template_name = VALUES(template_name),
          subject = VALUES(subject),
          body = VALUES(body),
          html_body = VALUES(html_body),
          variables = VALUES(variables)
      `, [template.key, template.name, template.category, template.subject, template.body, template.html_body, template.variables]);
    }
    logger.info('✅ Default email notification templates created/verified');
 
    // Insert default WhatsApp notification templates with complete messages
    const whatsappTemplates = [
      {
        key: 'welcome',
        name: 'Welcome Message',
        category: 'tenant',
        message: `🎉 *Welcome to {{platform_name}}!*
 
Hello {{tenant_name}}!
 
Your account has been created successfully.
 
📌 *Your Details:*
• Subdomain: {{subdomain}}
• Plan: {{plan_name}}
• Trial: {{trial_days}} days
 
🔗 Login: {{login_url}}
 
Need help? Contact us at {{support_email}}`,
        variables: '["tenant_name", "platform_name", "subdomain", "plan_name", "login_url", "trial_days", "support_email"]'
      },
      {
        key: 'password_reset',
        name: 'Password Reset',
        category: 'security',
        message: `🔐 *Password Reset Request*
 
Hello {{tenant_name}},
 
You requested a password reset. Click the link below:
 
{{reset_link}}
 
⏰ This link expires in {{expiry_hours}} hour(s).
 
If you didn't request this, please ignore this message.`,
        variables: '["tenant_name", "reset_link", "expiry_hours"]'
      },
      {
        key: 'payment_confirmation',
        name: 'Payment Confirmation',
        category: 'subscription',
        message: `✅ *Payment Confirmed!*
 
Hello {{tenant_name}},
 
Your payment has been processed successfully.
 
📋 *Details:*
• Plan: {{plan_name}}
• Amount: {{amount}}
• Date: {{payment_date}}
• Next billing: {{next_billing_date}}
 
Thank you for your business!`,
        variables: '["tenant_name", "plan_name", "amount", "payment_date", "next_billing_date"]'
      },
      {
        key: 'plan_expiring_soon',
        name: 'Plan Expiring Soon',
        category: 'subscription',
        message: `⚠️ *Plan Expiring Soon*
 
Hello {{tenant_name}},
 
Your *{{plan_name}}* plan expires in *{{days_remaining}} days* on {{expiry_date}}.
 
Renew now to avoid service interruption:
{{renewal_link}}`,
        variables: '["tenant_name", "plan_name", "days_remaining", "expiry_date", "renewal_link"]'
      },
      {
        key: 'plan_expired',
        name: 'Plan Expired',
        category: 'subscription',
        message: `🚨 *Plan Expired*
 
Hello {{tenant_name}},
 
Your *{{plan_name}}* plan has expired on {{expiry_date}}.
 
⏰ You have *{{grace_days}} days* grace period before suspension.
 
Renew now: {{renewal_link}}`,
        variables: '["tenant_name", "plan_name", "expiry_date", "renewal_link", "grace_days"]'
      },
      {
        key: 'account_suspended',
        name: 'Account Suspended',
        category: 'system',
        message: `🔴 *Account Suspended*
 
Hello {{tenant_name}},
 
Your account has been suspended.
 
📋 *Reason:* {{suspension_reason}}
 
To reactivate, contact: {{support_email}}`,
        variables: '["tenant_name", "suspension_reason", "support_email"]'
      },
      {
        key: 'account_reactivated',
        name: 'Account Reactivated',
        category: 'system',
        message: `🟢 *Account Reactivated!*
 
Hello {{tenant_name}},
 
Great news! Your account is now active.
 
📋 *Plan:* {{plan_name}}
 
Login now: {{login_url}}`,
        variables: '["tenant_name", "plan_name", "login_url"]'
      }
    ];
 
    // DISABLED: Auto-creation of WhatsApp templates removed per user request
    // Templates should be created manually by users as needed
    /*
    for (const template of whatsappTemplates) {
      await connection.execute(`
        INSERT INTO whatsapp_notification_templates (template_key, template_name, category, message, variables)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
          template_name = VALUES(template_name),
          message = VALUES(message),
          variables = VALUES(variables)
      `, [template.key, template.name, template.category, template.message, template.variables]);
    }
    */
    logger.info('✅ WhatsApp notification templates table ready (auto-creation disabled)');
 
    // ============================================
    // System Tenant Creation - REMOVED
    // ============================================
    // System tenant creation has been disabled and removed
    logger.info('⚠️  System tenant creation disabled');
 
    // Run WhatsApp tables migration
    logger.info('📱 Running WhatsApp tables migration...');
    const whatsappMigrationPath = path.join(
      __dirname,
      '../migrations/20241218_create_whatsapp_tables.sql'
    );
 
    if (fs.existsSync(whatsappMigrationPath)) {
      try {
        const whatsappMigration = fs.readFileSync(whatsappMigrationPath, 'utf8');
 
        // Remove all comment lines and empty lines
        const cleanedSQL = whatsappMigration
          .split('\n')
          .filter((line) => {
            const trimmed = line.trim();
            return trimmed.length > 0 && !trimmed.startsWith('--');
          })
          .join('\n');
 
        // Split by semicolon and filter valid statements
        const statements = cleanedSQL
          .split(';')
          .map((stmt) => stmt.trim())
          .filter((stmt) => {
            const upper = stmt.toUpperCase();
            return (
              stmt.length > 0 &&
              (upper.startsWith('CREATE TABLE') ||
                upper.startsWith('CREATE INDEX') ||
                upper.startsWith('ALTER TABLE'))
            );
          });
 
        logger.info(`Found ${statements.length} WhatsApp migration statements`);
 
        for (const statement of statements) {
          try {
            await connection.execute(statement);
          } catch (stmtError) {
            // Ignore if table/index already exists
            if (
              stmtError.code !== 'ER_TABLE_EXISTS_ERROR' &&
              stmtError.code !== 'ER_DUP_KEYNAME'
            ) {
              logger.warn('WhatsApp migration statement warning', {
                error: stmtError.message,
                code: stmtError.code,
              });
            }
          }
        }
        logger.info('✅ WhatsApp tables migration completed');
      } catch (migrationError) {
        logger.error('Error running WhatsApp migration', {
          error: migrationError.message,
          stack: migrationError.stack,
        });
        // Don't throw - allow server to continue
      }
    } else {
      logger.warn('⚠️ WhatsApp migration file not found');
    }
 
    // Run Plan Features migration
    logger.info('📦 Running Plan Features migration...');
    const planFeaturesMigrationPath = path.join(
      __dirname,
      '../migrations/20241220_add_plan_features.sql'
    );
 
    if (fs.existsSync(planFeaturesMigrationPath)) {
      try {
        const planFeaturesMigration = fs.readFileSync(planFeaturesMigrationPath, 'utf8');
 
        // Remove all comment lines and empty lines
        const cleanedSQL = planFeaturesMigration
          .split('\n')
          .filter((line) => {
            const trimmed = line.trim();
            return trimmed.length > 0 && !trimmed.startsWith('--');
          })
          .join('\n');
 
        // Split by semicolon and filter valid statements
        const statements = cleanedSQL
          .split(';')
          .map((stmt) => stmt.trim())
          .filter((stmt) => {
            const upper = stmt.toUpperCase();
            return stmt.length > 0 && upper.startsWith('ALTER TABLE');
          });
 
        logger.info(`Found ${statements.length} Plan Features migration statements`);
 
        for (const statement of statements) {
          try {
            await connection.execute(statement);
          } catch (stmtError) {
            // Ignore if column already exists
            if (stmtError.code === 'ER_DUP_FIELDNAME') {
              logger.info('Column already exists, skipping...');
            } else if (
              stmtError.code !== 'ER_TABLE_EXISTS_ERROR' &&
              stmtError.code !== 'ER_DUP_KEYNAME'
            ) {
              logger.warn('Plan Features migration statement warning', {
                error: stmtError.message,
                code: stmtError.code,
              });
            }
          }
        }
        logger.info('✅ Plan Features migration completed');
      } catch (migrationError) {
        logger.error('Error running Plan Features migration', {
          error: migrationError.message,
          stack: migrationError.stack,
        });
        // Don't throw - allow server to continue
      }
    } else {
      logger.warn('⚠️ Plan Features migration file not found');
    }
 
    // Run Payment Gateways migration
    logger.info('💳 Running Payment Gateways migration...');
    const paymentGatewaysMigrationPath = path.join(
      __dirname,
      '../migrations/20241220_update_payment_gateways.sql'
    );
 
    if (fs.existsSync(paymentGatewaysMigrationPath)) {
      try {
        const paymentGatewaysMigration = fs.readFileSync(paymentGatewaysMigrationPath, 'utf8');
 
        // Remove all comment lines and empty lines
        const cleanedSQL = paymentGatewaysMigration
          .split('\n')
          .filter((line) => {
            const trimmed = line.trim();
            return trimmed.length > 0 && !trimmed.startsWith('--');
          })
          .join('\n');
 
        // Split by semicolon and filter valid statements
        const statements = cleanedSQL
          .split(';')
          .map((stmt) => stmt.trim())
          .filter((stmt) => {
            const upper = stmt.toUpperCase();
            return stmt.length > 0 && upper.startsWith('ALTER TABLE');
          });
 
        logger.info(`Found ${statements.length} Payment Gateways migration statements`);
 
        for (const statement of statements) {
          try {
            await connection.execute(statement);
          } catch (stmtError) {
            // Ignore if column already exists
            if (stmtError.code === 'ER_DUP_FIELDNAME') {
              logger.info('Column already exists, skipping...');
            } else if (
              stmtError.code !== 'ER_TABLE_EXISTS_ERROR' &&
              stmtError.code !== 'ER_DUP_KEYNAME'
            ) {
              logger.warn('Payment Gateways migration statement warning', {
                error: stmtError.message,
                code: stmtError.code,
              });
            }
          }
        }
        logger.info('✅ Payment Gateways migration completed');
      } catch (migrationError) {
        logger.error('Error running Payment Gateways migration', {
          error: migrationError.message,
          stack: migrationError.stack,
        });
        // Don't throw - allow server to continue
      }
    } else {
      logger.warn('⚠️ Payment Gateways migration file not found');
    }
 
    // Run SuperAdmin Translations migration
    logger.info('🌐 Running SuperAdmin Translations migration...');
    const superadminTranslationsMigrationPath = path.join(
      __dirname,
      '../migrations/20241220_superadmin_translations.sql'
    );
 
    if (fs.existsSync(superadminTranslationsMigrationPath)) {
      try {
        const superadminTranslationsMigration = fs.readFileSync(superadminTranslationsMigrationPath, 'utf8');
 
        // Remove all comment lines and empty lines
        const cleanedSQL = superadminTranslationsMigration
          .split('\n')
          .filter((line) => {
            const trimmed = line.trim();
            return trimmed.length > 0 && !trimmed.startsWith('--');
          })
          .join('\n');
 
        // Split by semicolon and filter valid statements
        const statements = cleanedSQL
          .split(';')
          .map((stmt) => stmt.trim())
          .filter((stmt) => {
            const upper = stmt.toUpperCase();
            return stmt.length > 0 && upper.startsWith('INSERT');
          });
 
        logger.info(`Found ${statements.length} SuperAdmin Translations migration statements`);
 
        for (const statement of statements) {
          try {
            await connection.execute(statement);
          } catch (stmtError) {
            // Ignore if translation already exists
            if (stmtError.code === 'ER_DUP_ENTRY') {
              logger.info('Translation already exists, skipping...');
            } else {
              logger.warn('SuperAdmin Translations migration statement warning', {
                error: stmtError.message,
                code: stmtError.code,
              });
            }
          }
        }
        logger.info('✅ SuperAdmin Translations migration completed');
      } catch (migrationError) {
        logger.error('Error running SuperAdmin Translations migration', {
          error: migrationError.message,
          stack: migrationError.stack,
        });
        // Don't throw - allow server to continue
      }
    } else {
      logger.warn('⚠️ SuperAdmin Translations migration file not found');
    }
 
    // Run System Settings migration
    logger.info('⚙️ Running System Settings migration...');
    const systemSettingsMigrationPath = path.join(
      __dirname,
      '../migrations/20241220_system_settings.sql'
    );
 
    if (fs.existsSync(systemSettingsMigrationPath)) {
      try {
        const systemSettingsMigration = fs.readFileSync(systemSettingsMigrationPath, 'utf8');
 
        // Remove all comment lines and empty lines
        const cleanedSQL = systemSettingsMigration
          .split('\n')
          .filter((line) => {
            const trimmed = line.trim();
            return trimmed.length > 0 && !trimmed.startsWith('--');
          })
          .join('\n');
 
        // Split by semicolon and filter valid statements
        const statements = cleanedSQL
          .split(';')
          .map((stmt) => stmt.trim())
          .filter((stmt) => stmt.length > 0);
 
        logger.info(`Found ${statements.length} System Settings migration statements`);
 
        for (const statement of statements) {
          try {
            await connection.execute(statement);
          } catch (stmtError) {
            // Ignore if already exists
            if (stmtError.code === 'ER_DUP_ENTRY' || stmtError.code === 'ER_TABLE_EXISTS_ERROR') {
              logger.info('System setting already exists, skipping...');
            } else {
              logger.warn('System Settings migration statement warning', {
                error: stmtError.message,
                code: stmtError.code,
              });
            }
          }
        }
        logger.info('✅ System Settings migration completed');
      } catch (migrationError) {
        logger.error('Error running System Settings migration', {
          error: migrationError.message,
          stack: migrationError.stack,
        });
        // Don't throw - allow server to continue
      }
    } else {
      logger.warn('⚠️ System Settings migration file not found');
    }
 
    // Create mass_send_history table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS mass_send_history (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        recipients JSON NOT NULL,
        total_recipients INT DEFAULT 0,
        sent_count INT DEFAULT 0,
        failed_count INT DEFAULT 0,
        send_interval INT DEFAULT 70,
        status ENUM('pending', 'sending', 'paused', 'completed', 'cancelled', 'failed') DEFAULT 'pending',
        archived BOOLEAN DEFAULT FALSE,
        evolution_instance_id INT NULL,
        created_by INT,
        started_at TIMESTAMP NULL,
        completed_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_archived (archived),
        INDEX idx_evolution_instance (evolution_instance_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ mass_send_history table created/verified');
 
    // Add evolution_instance_id column if it doesn't exist (for existing databases)
    // NOTE: Foreign key constraint will be added after evolution_instances table is created
    try {
      await connection.execute(`
        ALTER TABLE mass_send_history 
        ADD COLUMN evolution_instance_id INT NULL AFTER archived
      `);
      logger.info('✅ Added evolution_instance_id column to mass_send_history');
    } catch (e) {
      if (e.code !== 'ER_DUP_FIELDNAME') {
        logger.warn('evolution_instance_id column:', e.message);
      }
    }
 
    // Create mass_send_schedules table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS mass_send_schedules (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        recipients JSON NOT NULL,
        total_recipients INT DEFAULT 0,
        sent_count INT DEFAULT 0,
        failed_count INT DEFAULT 0,
        send_interval INT DEFAULT 70,
        scheduled_date TIMESTAMP NOT NULL,
        status ENUM('scheduled', 'sending', 'completed', 'cancelled', 'failed') DEFAULT 'scheduled',
        evolution_instance_id INT NULL,
        created_by INT,
        started_at TIMESTAMP NULL,
        completed_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_scheduled_date (scheduled_date),
        INDEX idx_evolution_instance (evolution_instance_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ mass_send_schedules table created/verified');
 
    // Add evolution_instance_id column if it doesn't exist (for existing databases)
    // NOTE: Foreign key constraint will be added after evolution_instances table is created
    try {
      await connection.execute(`
        ALTER TABLE mass_send_schedules 
        ADD COLUMN evolution_instance_id INT NULL AFTER status
      `);
      logger.info('✅ Added evolution_instance_id column to mass_send_schedules');
    } catch (e) {
      if (e.code !== 'ER_DUP_FIELDNAME') {
        logger.warn('evolution_instance_id column:', e.message);
      }
    }
 
    // Create mass_send_reminders table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS mass_send_reminders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        recipients JSON NOT NULL,
        total_recipients INT DEFAULT 0,
        total_sent INT DEFAULT 0,
        send_interval INT DEFAULT 70,
        final_date DATE NOT NULL,
        reminder_dates JSON NOT NULL,
        next_send_at TIMESTAMP NULL,
        last_sent_at TIMESTAMP NULL,
        status ENUM('active', 'completed', 'cancelled') DEFAULT 'active',
        evolution_instance_id INT NULL,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_next_send_at (next_send_at),
        INDEX idx_evolution_instance (evolution_instance_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ mass_send_reminders table created/verified');
 
    // Add evolution_instance_id column if it doesn't exist (for existing databases)
    // NOTE: Foreign key constraint will be added after evolution_instances table is created
    try {
      await connection.execute(`
        ALTER TABLE mass_send_reminders 
        ADD COLUMN evolution_instance_id INT NULL AFTER status
      `);
      logger.info('✅ Added evolution_instance_id column to mass_send_reminders');
    } catch (e) {
      if (e.code !== 'ER_DUP_FIELDNAME') {
        logger.warn('evolution_instance_id column:', e.message);
      }
    }
 
    // Create mass_send_logs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS mass_send_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        send_type ENUM('history', 'schedule', 'reminder') NOT NULL,
        send_id INT NOT NULL,
        phone_number VARCHAR(20) NOT NULL,
        contact_name VARCHAR(255),
        message TEXT,
        status ENUM('pending', 'sending', 'sent', 'success', 'failed') DEFAULT 'pending',
        error_message TEXT,
        sent_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_send_type_id (send_type, send_id),
        INDEX idx_phone (phone_number),
        INDEX idx_status (status),
        INDEX idx_sent_at (sent_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ mass_send_logs table created/verified');
 
    // Add email support columns to mass_send tables
    try {
      // Check and add columns to mass_send_history
      const [historyColumns] = await connection.execute(
        `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'mass_send_history'`
      );
      const historyColumnNames = new Set(historyColumns.map(col => col.COLUMN_NAME));
      
      if (!historyColumnNames.has('channel')) {
        await connection.execute(`ALTER TABLE mass_send_history ADD COLUMN channel VARCHAR(20) DEFAULT 'whatsapp' AFTER status`);
        logger.info('✅ Added channel column to mass_send_history');
      }
      if (!historyColumnNames.has('email_account_id')) {
        await connection.execute(`ALTER TABLE mass_send_history ADD COLUMN email_account_id INT DEFAULT NULL AFTER channel`);
        logger.info('✅ Added email_account_id column to mass_send_history');
      }
      if (!historyColumnNames.has('email_subject')) {
        await connection.execute(`ALTER TABLE mass_send_history ADD COLUMN email_subject VARCHAR(255) DEFAULT NULL AFTER email_account_id`);
        logger.info('✅ Added email_subject column to mass_send_history');
      }
 
      // Check and add columns to mass_send_schedules
      const [schedulesColumns] = await connection.execute(
        `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'mass_send_schedules'`
      );
      const schedulesColumnNames = new Set(schedulesColumns.map(col => col.COLUMN_NAME));
      
      if (!schedulesColumnNames.has('channel')) {
        await connection.execute(`ALTER TABLE mass_send_schedules ADD COLUMN channel VARCHAR(20) DEFAULT 'whatsapp' AFTER status`);
        logger.info('✅ Added channel column to mass_send_schedules');
      }
      if (!schedulesColumnNames.has('email_account_id')) {
        await connection.execute(`ALTER TABLE mass_send_schedules ADD COLUMN email_account_id INT DEFAULT NULL AFTER channel`);
        logger.info('✅ Added email_account_id column to mass_send_schedules');
      }
      if (!schedulesColumnNames.has('email_subject')) {
        await connection.execute(`ALTER TABLE mass_send_schedules ADD COLUMN email_subject VARCHAR(255) DEFAULT NULL AFTER email_account_id`);
        logger.info('✅ Added email_subject column to mass_send_schedules');
      }
 
      // Check and add columns to mass_send_reminders
      const [remindersColumns] = await connection.execute(
        `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'mass_send_reminders'`
      );
      const remindersColumnNames = new Set(remindersColumns.map(col => col.COLUMN_NAME));
      
      if (!remindersColumnNames.has('channel')) {
        await connection.execute(`ALTER TABLE mass_send_reminders ADD COLUMN channel VARCHAR(20) DEFAULT 'whatsapp' AFTER status`);
        logger.info('✅ Added channel column to mass_send_reminders');
      }
      if (!remindersColumnNames.has('email_account_id')) {
        await connection.execute(`ALTER TABLE mass_send_reminders ADD COLUMN email_account_id INT DEFAULT NULL AFTER channel`);
        logger.info('✅ Added email_account_id column to mass_send_reminders');
      }
      if (!remindersColumnNames.has('email_subject')) {
        await connection.execute(`ALTER TABLE mass_send_reminders ADD COLUMN email_subject VARCHAR(255) DEFAULT NULL AFTER email_account_id`);
        logger.info('✅ Added email_subject column to mass_send_reminders');
      }
 
      logger.info('✅ Email support columns verified/added to mass_send tables');
    } catch (error) {
      logger.error('Error adding email support columns to mass_send tables', { error: error.message });
    }
 
    // Create invoice_clients table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS invoice_clients (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(100) NOT NULL,
        email VARCHAR(255) NOT NULL,
        phone VARCHAR(20) NOT NULL,
        company_name VARCHAR(150),
        tax_id VARCHAR(50),
        address VARCHAR(500),
        city VARCHAR(100),
        state VARCHAR(50),
        zip_code VARCHAR(20),
        country VARCHAR(50) DEFAULT 'Brazil',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_email (tenant_id, email),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_email (email),
        INDEX idx_phone (phone),
        INDEX idx_name (name)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ invoice_clients table created/verified');
 
    // Create invoices table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS invoices (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        invoice_number VARCHAR(50) NOT NULL,
        type ENUM('invoice', 'quote') NOT NULL DEFAULT 'invoice',
        client_id INT NOT NULL,
        title VARCHAR(200) NOT NULL,
        description TEXT,
        currency VARCHAR(3) DEFAULT 'USD',
        subtotal DECIMAL(10,2) DEFAULT 0.00,
        tax_rate DECIMAL(5,2) DEFAULT 0.00,
        tax_amount DECIMAL(10,2) DEFAULT 0.00,
        discount_type ENUM('fixed', 'percentage') DEFAULT 'fixed',
        discount_value DECIMAL(10,2) DEFAULT 0.00,
        discount_amount DECIMAL(10,2) DEFAULT 0.00,
        total_amount DECIMAL(10,2) DEFAULT 0.00,
        status ENUM('draft', 'sent', 'viewed', 'accepted', 'rejected', 'paid', 'cancelled', 'archived') DEFAULT 'draft',
        rejection_reason TEXT,
        payment_method ENUM('paypal', 'pagseguro', 'bank_transfer', 'cash', 'other') DEFAULT 'paypal',
        payment_link VARCHAR(500),
        payment_id VARCHAR(100),
        payment_gateway_response JSON,
        due_date DATE,
        notes TEXT,
        terms TEXT,
        sent_at TIMESTAMP NULL,
        viewed_at TIMESTAMP NULL,
        accepted_at TIMESTAMP NULL,
        rejected_at TIMESTAMP NULL,
        paid_at TIMESTAMP NULL,
        converted_to_invoice_id INT,
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_invoice (tenant_id, invoice_number),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (client_id) REFERENCES invoice_clients(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_invoice_number (invoice_number),
        INDEX idx_client (client_id),
        INDEX idx_status (status),
        INDEX idx_type (type),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ invoices table created/verified');
 
    // Create invoice_items table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS invoice_items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        invoice_id INT NOT NULL,
        description VARCHAR(255) NOT NULL,
        quantity DECIMAL(10,2) NOT NULL DEFAULT 1.00,
        unit_price DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        total_price DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE,
        INDEX idx_invoice (invoice_id),
        INDEX idx_sort (sort_order)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ invoice_items table created/verified');
 
    // Create invoice_logs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS invoice_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        invoice_id INT NOT NULL,
        action ENUM('created', 'sent', 'viewed', 'accepted', 'rejected', 'paid', 'cancelled', 'updated', 'payment_created', 'payment_confirmed', 'converted_to_invoice', 'archived', 'reactivated') NOT NULL,
        actor_type ENUM('admin', 'client', 'system') NOT NULL,
        actor_id INT,
        details TEXT,
        ip_address VARCHAR(45),
        user_agent TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE,
        INDEX idx_invoice (invoice_id),
        INDEX idx_action (action),
        INDEX idx_actor_type (actor_type),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ invoice_logs table created/verified');
 
    // Create invoice_access_tokens table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS invoice_access_tokens (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        invoice_id INT NOT NULL,
        token VARCHAR(64) UNIQUE NOT NULL,
        email VARCHAR(255) NOT NULL,
        expires_at TIMESTAMP NOT NULL,
        used_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_invoice (invoice_id),
        INDEX idx_token (token),
        INDEX idx_email (email),
        INDEX idx_expires_at (expires_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ invoice_access_tokens table created/verified');
 
    // Create chat_widgets table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS chat_widgets (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        name VARCHAR(100) NOT NULL,
        whatsapp_number VARCHAR(20) NOT NULL,
        button_title VARCHAR(50) NOT NULL DEFAULT 'Chat with us',
        button_background_color VARCHAR(7) NOT NULL DEFAULT '#25D366',
        widget_title VARCHAR(100) NOT NULL DEFAULT 'How can we help you?',
        predefined_message TEXT,
        max_message_length INT DEFAULT 500,
        margin_right INT DEFAULT 20,
        margin_bottom INT DEFAULT 20,
        border_radius INT DEFAULT 50,
        widget_token VARCHAR(64) UNIQUE NOT NULL,
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_token (widget_token),
        INDEX idx_active (is_active),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ chat_widgets table created/verified');
 
    // Create widget_analytics table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS widget_analytics (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        widget_id INT NOT NULL,
        event_type ENUM('loaded', 'opened', 'closed', 'message_sent', 'clicked') NOT NULL,
        event_data JSON,
        ip_address VARCHAR(45),
        user_agent TEXT,
        referrer_url VARCHAR(500),
        page_url VARCHAR(500),
        session_id VARCHAR(64),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (widget_id) REFERENCES chat_widgets(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_widget (widget_id),
        INDEX idx_event_type (event_type),
        INDEX idx_session (session_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ widget_analytics table created/verified');
 
    // Create tenant_profiles table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS tenant_profiles (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL UNIQUE,
        logo_url VARCHAR(500),
        primary_color VARCHAR(7) DEFAULT '#00a149',
        primary_dark VARCHAR(7) DEFAULT '#654321',
        primary_light VARCHAR(7) DEFAULT '#A0522D',
        accent_color VARCHAR(7) DEFAULT '#CD853F',
        text_color VARCHAR(7) DEFAULT '#333333',
        text_light VARCHAR(7) DEFAULT '#666666',
        bg_color VARCHAR(7) DEFAULT '#f5f5f5',
        white VARCHAR(7) DEFAULT '#ffffff',
        success VARCHAR(7) DEFAULT '#28a745',
        warning VARCHAR(7) DEFAULT '#ffc107',
        danger VARCHAR(7) DEFAULT '#dc3545',
        info VARCHAR(7) DEFAULT '#17a2b8',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ tenant_profiles table created/verified');
 
    // Create WhatsApp Cloud tables
    logger.info('📱 Creating WhatsApp Cloud tables...');
 
    // Create whatsapp_cloud_conversations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_conversations (
        id INT PRIMARY KEY AUTO_INCREMENT,
        tenant_id INT NOT NULL,
        account_id INT,
        contact_phone VARCHAR(50) NOT NULL,
        contact_name VARCHAR(255),
        contact_avatar TEXT,
        last_message TEXT,
        last_message_time DATETIME,
        last_message_type ENUM('text', 'image', 'document', 'audio', 'video', 'location', 'contact', 'sticker') DEFAULT 'text',
        source ENUM('whatsapp_cloud', 'whatsapp_web') DEFAULT 'whatsapp_cloud',
        status ENUM('active', 'archived', 'closed') DEFAULT 'active',
        claimed_by_user_id INT,
        claimed_at DATETIME,
        store_id INT,
        department_id INT,
        stage_id VARCHAR(50) DEFAULT 'unassigned',
        priority ENUM('low', 'normal', 'high', 'urgent') DEFAULT 'normal',
        tags JSON,
        notes JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (claimed_by_user_id) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_account_id (account_id),
        INDEX idx_contact_phone (contact_phone),
        INDEX idx_claimed_by (claimed_by_user_id),
        INDEX idx_status (status),
        INDEX idx_stage (stage_id),
        INDEX idx_last_message_time (last_message_time)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_conversations table created/verified');
 
    // Create whatsapp_cloud_messages table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_messages (
        id INT PRIMARY KEY AUTO_INCREMENT,
        tenant_id INT NOT NULL,
        conversation_id INT NOT NULL,
        message_id VARCHAR(255),
        content TEXT,
        text_content TEXT,
        direction ENUM('inbound', 'outbound') DEFAULT 'inbound',
        message_type ENUM('text', 'image', 'document', 'audio', 'video', 'location', 'contact', 'sticker', 'product', 'invoice') DEFAULT 'text',
        sender_type ENUM('customer', 'agent', 'system', 'bot') DEFAULT 'customer',
        sender_id INT,
        sent_by_user_id INT,
        media_url TEXT,
        media_filename VARCHAR(255),
        filename VARCHAR(255),
        media_mime_type VARCHAR(100),
        caption TEXT,
        timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        status ENUM('sent', 'delivered', 'read', 'failed') DEFAULT 'sent',
        is_internal_note BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (conversation_id) REFERENCES whatsapp_cloud_conversations(id) ON DELETE CASCADE,
        FOREIGN KEY (sender_id) REFERENCES users(id) ON DELETE SET NULL,
        FOREIGN KEY (sent_by_user_id) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_conversation_id (conversation_id),
        INDEX idx_message_id (message_id),
        INDEX idx_sender_type (sender_type),
        INDEX idx_direction (direction),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_messages table created/verified');
 
    // Add missing columns to whatsapp_cloud_messages if they don't exist
    const [messageColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_cloud_messages'
    `);
    const existingMessageColumns = messageColumns.map(col => col.COLUMN_NAME);
 
    if (!existingMessageColumns.includes('text_content')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN text_content TEXT NULL`);
        logger.info('✅ Added text_content column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('text_content column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('direction')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN direction ENUM('inbound', 'outbound') DEFAULT 'inbound'`);
        logger.info('✅ Added direction column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('direction column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('sent_by_user_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN sent_by_user_id INT NULL`);
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD CONSTRAINT fk_messages_sent_by_user FOREIGN KEY (sent_by_user_id) REFERENCES users(id) ON DELETE SET NULL`);
        logger.info('✅ Added sent_by_user_id column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME' && e.code !== 'ER_DUP_KEYNAME') {
          logger.warn('sent_by_user_id column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('filename')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN filename VARCHAR(255) NULL`);
        logger.info('✅ Added filename column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('filename column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('timestamp')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP`);
        logger.info('✅ Added timestamp column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('timestamp column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('tenant_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN tenant_id INT NULL`);
        logger.info('✅ Added tenant_id column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('tenant_id column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('account_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN account_id INT NULL`);
        logger.info('✅ Added account_id column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('account_id column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('from_phone')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN from_phone VARCHAR(30) NULL`);
        logger.info('✅ Added from_phone column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('from_phone column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('to_phone')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN to_phone VARCHAR(30) NULL`);
        logger.info('✅ Added to_phone column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('to_phone column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('text_body')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN text_body TEXT NULL`);
        logger.info('✅ Added text_body column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('text_body column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('content')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN content TEXT NULL`);
        logger.info('✅ Added content column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('content column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('sender_id')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN sender_id INT NULL`);
        logger.info('✅ Added sender_id column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('sender_id column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('sender_type')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN sender_type ENUM('customer', 'agent', 'system', 'bot') DEFAULT 'customer'`);
        logger.info('✅ Added sender_type column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('sender_type column:', e.message);
        }
      }
    }
 
    if (!existingMessageColumns.includes('updated_at')) {
      try {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`);
        logger.info('✅ Added updated_at column to whatsapp_cloud_messages');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('updated_at column:', e.message);
        }
      }
    }
 
    // Create conversation_notes table for robust note tracking
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS conversation_notes (
        id INT PRIMARY KEY AUTO_INCREMENT,
        tenant_id INT NOT NULL,
        conversation_id INT NOT NULL,
        contact_phone VARCHAR(50) NOT NULL,
        note_text TEXT NOT NULL,
        note_type ENUM('transfer', 'general', 'system') DEFAULT 'general',
        created_by_user_id INT,
        created_by_name VARCHAR(255),
        transfer_from_department VARCHAR(255),
        transfer_to_department VARCHAR(255),
        transfer_from_store VARCHAR(255),
        transfer_to_store VARCHAR(255),
        is_visible_to_users BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by_user_id) REFERENCES users(id) ON DELETE SET NULL,
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_conversation_id (conversation_id),
        INDEX idx_contact_phone (contact_phone),
        INDEX idx_created_by (created_by_user_id),
        INDEX idx_note_type (note_type),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ conversation_notes table created/verified');
 
    // Add caption column if it doesn't exist (for existing installations)
    try {
      const [columns] = await connection.execute(`
        SELECT COLUMN_NAME 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'whatsapp_cloud_messages' 
          AND COLUMN_NAME = 'caption'
      `);
      
      if (columns.length === 0) {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_messages 
          ADD COLUMN caption TEXT NULL 
          AFTER media_mime_type
        `);
        logger.info('✅ Added caption column to existing whatsapp_cloud_messages table');
      }
      
      // Update message_type enum to include product and invoice types
      await connection.execute(`
        ALTER TABLE whatsapp_cloud_messages 
        MODIFY COLUMN message_type ENUM('text', 'image', 'document', 'audio', 'video', 'location', 'contact', 'sticker', 'product', 'invoice') DEFAULT 'text'
      `);
      logger.info('✅ Updated message_type enum with product and invoice types');
    } catch (alterError) {
      // Log but don't fail - table might already be up to date
      logger.warn('Could not update whatsapp_cloud_messages table structure:', alterError.message);
    }
 
    // Create pipeline_stages table for tenant-defined stages
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS pipeline_stages (
        id INT PRIMARY KEY AUTO_INCREMENT,
        tenant_id INT NOT NULL,
        stage_key VARCHAR(50) NOT NULL,
        stage_name VARCHAR(100) NOT NULL,
        stage_color VARCHAR(7) DEFAULT '#6b7280',
        stage_icon VARCHAR(50) DEFAULT 'fas fa-circle',
        stage_order INT DEFAULT 0,
        is_default BOOLEAN DEFAULT FALSE,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        UNIQUE KEY unique_tenant_stage (tenant_id, stage_key),
        INDEX idx_tenant_id (tenant_id),
        INDEX idx_stage_order (stage_order),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ pipeline_stages table created/verified');
 
    // Insert default pipeline stages for all tenants
    try {
      const [tenants] = await connection.execute('SELECT id FROM tenants');
      
      const defaultStages = [
        { key: 'unassigned', name: 'Unassigned', color: '#6b7280', icon: 'fas fa-inbox', order: 0 },
        { key: 'new', name: 'New', color: '#3b82f6', icon: 'fas fa-star', order: 1 },
        { key: 'negotiation', name: 'Negotiation', color: '#f59e0b', icon: 'fas fa-handshake', order: 2 },
        { key: 'won', name: 'Won', color: '#10b981', icon: 'fas fa-trophy', order: 3 },
        { key: 'lost', name: 'Lost', color: '#ef4444', icon: 'fas fa-times-circle', order: 4 }
      ];
 
      for (const tenant of tenants) {
        for (const stage of defaultStages) {
          await connection.execute(`
            INSERT IGNORE INTO pipeline_stages (tenant_id, stage_key, stage_name, stage_color, stage_icon, stage_order, is_default)
            VALUES (?, ?, ?, ?, ?, ?, TRUE)
          `, [tenant.id, stage.key, stage.name, stage.color, stage.icon, stage.order]);
        }
      }
      
      logger.info('✅ Default pipeline stages inserted for all tenants');
    } catch (stageError) {
      logger.warn('⚠️ Error inserting default pipeline stages', { error: stageError.message });
    }
 
    logger.info('✅ WhatsApp Cloud tables created successfully');
 
    // Insert default placeholders for all tenants (if not exists)
    try {
      const [tenants] = await connection.execute('SELECT id FROM tenants');
      
      const defaultPlaceholders = [
        { key: '{{customer_name}}', value: 'Customer Name', description: 'Name of the customer' },
        { key: '{{store_name}}', value: 'Store Name', description: 'Name of the store' },
        { key: '{{business_hours}}', value: 'Business Hours', description: 'Store business hours' },
        { key: '{{store_phone}}', value: 'Store Phone', description: 'Store phone number' },
        { key: '{{store_address}}', value: 'Store Address', description: 'Store address' },
        { key: '{{current_date}}', value: 'Current Date', description: 'Current date' },
        { key: '{{current_time}}', value: 'Current Time', description: 'Current time' }
      ];
 
      for (const tenant of tenants) {
        for (const placeholder of defaultPlaceholders) {
          await connection.execute(`
            INSERT IGNORE INTO message_placeholders (tenant_id, placeholder_key, placeholder_value, description)
            VALUES (?, ?, ?, ?)
          `, [tenant.id, placeholder.key, placeholder.value, placeholder.description]);
        }
      }
      
      logger.info('✅ Default placeholders inserted for all tenants');
    } catch (placeholderError) {
      logger.warn('⚠️ Error inserting default placeholders', { error: placeholderError.message });
    }
 
    // Run Notification System migration
    logger.info('📧 Running Notification System migration...');
    const notificationMigrationPath = path.join(
      __dirname,
      '../migrations/20241221_notification_system.sql'
    );
 
    if (fs.existsSync(notificationMigrationPath)) {
      try {
        const notificationMigration = fs.readFileSync(notificationMigrationPath, 'utf8');
 
        // Remove all comment lines and empty lines
        const cleanedSQL = notificationMigration
          .split('\n')
          .filter((line) => {
            const trimmed = line.trim();
            return trimmed.length > 0 && !trimmed.startsWith('--');
          })
          .join('\n');
 
        // Split by semicolon and filter valid statements
        const statements = cleanedSQL
          .split(';')
          .map((stmt) => stmt.trim())
          .filter((stmt) => stmt.length > 0);
 
        logger.info(`Found ${statements.length} Notification System migration statements`);
 
        for (const statement of statements) {
          try {
            await connection.execute(statement);
          } catch (stmtError) {
            // Ignore if already exists
            if (stmtError.code === 'ER_DUP_ENTRY' || 
                stmtError.code === 'ER_TABLE_EXISTS_ERROR' ||
                stmtError.code === 'ER_DUP_FIELDNAME') {
              logger.info('Notification item already exists, skipping...');
            } else {
              logger.warn('Notification System migration statement warning', {
                error: stmtError.message,
                code: stmtError.code,
              });
            }
          }
        }
        logger.info('✅ Notification System migration completed');
      } catch (migrationError) {
        logger.error('Error running Notification System migration', {
          error: migrationError.message,
          stack: migrationError.stack,
        });
        // Don't throw - allow server to continue
      }
    } else {
      logger.warn('⚠️ Notification System migration file not found');
    }
 
    // ============================================
    // Additional Missing Tables for 97 Total
    // ============================================
 
    // Create conversation_logs table (critical for WhatsApp Cloud)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS conversation_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        conversation_id INT NOT NULL,
        tenant_id INT NOT NULL,
        user_id INT,
        action ENUM('claim', 'release', 'transfer', 'note_added', 'status_change') NOT NULL,
        details JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_conversation (conversation_id),
        INDEX idx_tenant (tenant_id),
        INDEX idx_user (user_id),
        INDEX idx_action (action),
        INDEX idx_created (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ conversation_logs table created/verified');
 
    // Create conversation_notes table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS conversation_notes (
        id INT AUTO_INCREMENT PRIMARY KEY,
        conversation_id INT NOT NULL,
        tenant_id INT NOT NULL,
        user_id INT NOT NULL,
        note TEXT NOT NULL,
        is_private BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_conversation (conversation_id),
        INDEX idx_tenant (tenant_id),
        INDEX idx_user (user_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ conversation_notes table created/verified');
 
    // Create conversation_transfers table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS conversation_transfers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        conversation_id INT NOT NULL,
        tenant_id INT NOT NULL,
        from_user_id INT,
        to_user_id INT,
        from_department_id INT,
        to_department_id INT,
        reason TEXT,
        status ENUM('pending', 'accepted', 'rejected') DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_conversation (conversation_id),
        INDEX idx_tenant (tenant_id),
        INDEX idx_from_user (from_user_id),
        INDEX idx_to_user (to_user_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ conversation_transfers table created/verified');
 
    // Create system_audit_logs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS system_audit_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        user_id INT,
        action VARCHAR(100) NOT NULL,
        table_name VARCHAR(100),
        record_id INT,
        old_values JSON,
        new_values JSON,
        ip_address VARCHAR(45),
        user_agent TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_user (user_id),
        INDEX idx_action (action),
        INDEX idx_table (table_name),
        INDEX idx_created (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ system_audit_logs table created/verified');
 
    // Create backup_configurations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS backup_configurations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        backup_type ENUM('full', 'incremental', 'differential') DEFAULT 'full',
        frequency ENUM('daily', 'weekly', 'monthly') DEFAULT 'daily',
        retention_days INT DEFAULT 30,
        storage_path VARCHAR(500),
        encryption_enabled BOOLEAN DEFAULT FALSE,
        compression_enabled BOOLEAN DEFAULT TRUE,
        last_backup_at TIMESTAMP NULL,
        next_backup_at TIMESTAMP NULL,
        status ENUM('active', 'inactive', 'error') DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_next_backup (next_backup_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ backup_configurations table created/verified');
 
    // Create backup_logs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS backup_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        configuration_id INT,
        backup_type VARCHAR(50),
        file_path VARCHAR(500),
        file_size BIGINT,
        status ENUM('started', 'completed', 'failed') DEFAULT 'started',
        error_message TEXT,
        duration_seconds INT,
        started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        completed_at TIMESTAMP NULL,
        INDEX idx_tenant (tenant_id),
        INDEX idx_config (configuration_id),
        INDEX idx_status (status),
        INDEX idx_started (started_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ backup_logs table created/verified');
 
    // Create api_rate_limits table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS api_rate_limits (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        endpoint_pattern VARCHAR(255) NOT NULL,
        method ENUM('GET', 'POST', 'PUT', 'DELETE', 'PATCH', '*') DEFAULT '*',
        requests_per_minute INT DEFAULT 60,
        requests_per_hour INT DEFAULT 1000,
        requests_per_day INT DEFAULT 10000,
        burst_limit INT DEFAULT 10,
        enabled BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_endpoint (endpoint_pattern),
        INDEX idx_enabled (enabled)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ api_rate_limits table created/verified');
 
    // Create api_rate_limit_logs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS api_rate_limit_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        api_key_id INT,
        endpoint VARCHAR(255),
        method VARCHAR(10),
        ip_address VARCHAR(45),
        requests_count INT DEFAULT 1,
        blocked BOOLEAN DEFAULT FALSE,
        reset_time TIMESTAMP,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_api_key (api_key_id),
        INDEX idx_endpoint (endpoint),
        INDEX idx_blocked (blocked),
        INDEX idx_created (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ api_rate_limit_logs table created/verified');
 
    // Create cdn_configurations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS cdn_configurations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        provider ENUM('cloudflare', 'aws', 'azure', 'custom') NOT NULL,
        endpoint_url VARCHAR(500) NOT NULL,
        api_key VARCHAR(255),
        api_secret VARCHAR(255),
        zone_id VARCHAR(255),
        cache_ttl INT DEFAULT 3600,
        compression_enabled BOOLEAN DEFAULT TRUE,
        minification_enabled BOOLEAN DEFAULT TRUE,
        enabled BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_provider (provider),
        INDEX idx_enabled (enabled)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ cdn_configurations table created/verified');
 
    // Create performance_metrics table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS performance_metrics (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        metric_type ENUM('response_time', 'memory_usage', 'cpu_usage', 'disk_usage', 'database_queries') NOT NULL,
        endpoint VARCHAR(255),
        value DECIMAL(10,4) NOT NULL,
        unit VARCHAR(20) DEFAULT 'ms',
        metadata JSON,
        recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_type (metric_type),
        INDEX idx_endpoint (endpoint),
        INDEX idx_recorded (recorded_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ performance_metrics table created/verified');
 
    // Create cache_configurations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS cache_configurations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        cache_key VARCHAR(255) NOT NULL,
        cache_type ENUM('redis', 'memcached', 'file', 'database') DEFAULT 'redis',
        ttl_seconds INT DEFAULT 3600,
        compression_enabled BOOLEAN DEFAULT FALSE,
        encryption_enabled BOOLEAN DEFAULT FALSE,
        tags JSON,
        enabled BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_cache_key (cache_key),
        INDEX idx_type (cache_type),
        INDEX idx_enabled (enabled)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ cache_configurations table created/verified');
 
    // Create security_logs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS security_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        user_id INT,
        event_type ENUM('login_success', 'login_failed', 'logout', 'password_change', 'permission_denied', 'suspicious_activity') NOT NULL,
        severity ENUM('low', 'medium', 'high', 'critical') DEFAULT 'medium',
        ip_address VARCHAR(45),
        user_agent TEXT,
        details JSON,
        resolved BOOLEAN DEFAULT FALSE,
        resolved_by INT,
        resolved_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_user (user_id),
        INDEX idx_event_type (event_type),
        INDEX idx_severity (severity),
        INDEX idx_resolved (resolved),
        INDEX idx_created (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ security_logs table created/verified');
 
    // Create monitoring_configurations table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS monitoring_configurations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT,
        monitor_name VARCHAR(255) NOT NULL,
        monitor_type ENUM('uptime', 'performance', 'error_rate', 'custom') NOT NULL,
        endpoint_url VARCHAR(500),
        check_interval_minutes INT DEFAULT 5,
        timeout_seconds INT DEFAULT 30,
        expected_status_code INT DEFAULT 200,
        alert_threshold DECIMAL(10,4),
        alert_email VARCHAR(255),
        alert_webhook VARCHAR(500),
        enabled BOOLEAN DEFAULT TRUE,
        last_check_at TIMESTAMP NULL,
        last_status ENUM('up', 'down', 'warning') DEFAULT 'up',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_tenant (tenant_id),
        INDEX idx_type (monitor_type),
        INDEX idx_enabled (enabled),
        INDEX idx_last_check (last_check_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ monitoring_configurations table created/verified');
 
    // Add missing columns to existing tables
    try {
      // Add last_read_at to whatsapp_cloud_messages if missing
      const [cloudMessageColumns] = await connection.query(`
        SELECT COLUMN_NAME 
        FROM information_schema.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'whatsapp_cloud_messages'
      `);
      const existingCloudMessageColumns = cloudMessageColumns.map(col => col.COLUMN_NAME);
 
      if (!existingCloudMessageColumns.includes('last_read_at')) {
        await connection.execute(`ALTER TABLE whatsapp_cloud_messages ADD COLUMN last_read_at TIMESTAMP NULL`);
        logger.info('✅ Added last_read_at column to whatsapp_cloud_messages');
      }
 
      // Add text_content to messages if missing
      const [messageColumns] = await connection.query(`
        SELECT COLUMN_NAME 
        FROM information_schema.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'messages'
      `);
      const existingMessageColumns = messageColumns.map(col => col.COLUMN_NAME);
 
      if (!existingMessageColumns.includes('text_content')) {
        await connection.execute(`ALTER TABLE messages ADD COLUMN text_content TEXT NULL`);
        logger.info('✅ Added text_content column to messages');
      }
    } catch (columnError) {
      logger.warn('Error adding missing columns:', columnError.message);
    }
 
    // Create pipeline_stages table (critical for conversations management)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS pipeline_stages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        stage_key VARCHAR(50) NOT NULL,
        stage_name VARCHAR(100) NOT NULL,
        stage_color VARCHAR(20) DEFAULT '#6b7280',
        stage_icon VARCHAR(50) DEFAULT 'fas fa-circle',
        stage_order INT DEFAULT 0,
        is_default BOOLEAN DEFAULT FALSE,
        active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_stage (tenant_id, stage_key),
        INDEX idx_tenant (tenant_id),
        INDEX idx_order (stage_order),
        INDEX idx_active (active),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ pipeline_stages table created/verified');
 
    // Insert default pipeline stages for all tenants
    const defaultStages = [
      { key: 'unassigned', name: 'Unassigned', color: '#6b7280', icon: 'fas fa-inbox', order: 1, is_default: true },
      { key: 'new', name: 'New', color: '#3b82f6', icon: 'fas fa-plus-circle', order: 2, is_default: true },
      { key: 'in_progress', name: 'In Progress', color: '#f59e0b', icon: 'fas fa-clock', order: 3, is_default: true },
      { key: 'waiting', name: 'Waiting', color: '#8b5cf6', icon: 'fas fa-pause-circle', order: 4, is_default: true },
      { key: 'resolved', name: 'Resolved', color: '#10b981', icon: 'fas fa-check-circle', order: 5, is_default: true },
      { key: 'closed', name: 'Closed', color: '#ef4444', icon: 'fas fa-times-circle', order: 6, is_default: true }
    ];
 
    // Get all tenants to insert default stages
    const [tenants] = await connection.execute('SELECT id FROM tenants WHERE id > 0');
    
    for (const tenant of tenants) {
      for (const stage of defaultStages) {
        await connection.execute(`
          INSERT IGNORE INTO pipeline_stages (tenant_id, stage_key, stage_name, stage_color, stage_icon, stage_order, is_default, active)
          VALUES (?, ?, ?, ?, ?, ?, ?, TRUE)
        `, [tenant.id, stage.key, stage.name, stage.color, stage.icon, stage.order, stage.is_default]);
      }
    }
    logger.info('✅ Default pipeline stages created/verified for all tenants');
 
    for (const stage of defaultStages) {
      await connection.execute(
        `UPDATE pipeline_stages
         SET stage_name = ?, stage_color = ?, stage_icon = ?, stage_order = ?
         WHERE stage_key = ?`,
        [stage.name, stage.color, stage.icon, stage.order, stage.key]
      );
    }
    logger.info('✅ Default pipeline stages updated to English');
 
    // ============================================
    // WhatsApp Cloud FAQ Tables
    // ============================================
    
    // Create whatsapp_cloud_faqs table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_faqs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NULL,
        question VARCHAR(500) NOT NULL,
        answer TEXT NOT NULL,
        keywords TEXT,
        emoji VARCHAR(10),
        category VARCHAR(50) DEFAULT 'general',
        active BOOLEAN DEFAULT TRUE,
        order_position INT DEFAULT 0,
        trigger_type ENUM('keyword', 'menu', 'auto') DEFAULT 'keyword',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_account (account_id),
        INDEX idx_active (active),
        INDEX idx_order (order_position),
        INDEX idx_category (category),
        INDEX idx_trigger_type (trigger_type)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_faqs table created/verified');
 
    // Create whatsapp_cloud_faq_usage table (tracks FAQ usage)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_faq_usage (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        faq_id INT NOT NULL,
        conversation_id INT NOT NULL,
        triggered_by ENUM('user', 'auto', 'menu') DEFAULT 'user',
        user_message TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (faq_id) REFERENCES whatsapp_cloud_faqs(id) ON DELETE CASCADE,
        FOREIGN KEY (conversation_id) REFERENCES whatsapp_cloud_conversations(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_faq (faq_id),
        INDEX idx_conversation (conversation_id),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_faq_usage table created/verified');
 
    // Create whatsapp_cloud_faq_settings table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_faq_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NULL,
        auto_reply_enabled BOOLEAN DEFAULT TRUE,
        menu_enabled BOOLEAN DEFAULT TRUE,
        menu_trigger_keyword VARCHAR(50) DEFAULT 'menu',
        welcome_message TEXT,
        no_match_message TEXT,
        menu_header TEXT,
        menu_footer TEXT,
        similarity_threshold DECIMAL(3,2) DEFAULT 0.70,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_account (tenant_id, account_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_account (account_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_faq_settings table created/verified');
 
    // Add missing columns to whatsapp_cloud_faqs table if they don't exist
    const [faqColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_cloud_faqs'
    `);
    const existingFaqColumns = faqColumns.map(col => col.COLUMN_NAME);
 
    if (!existingFaqColumns.includes('usage_count')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_faqs 
          ADD COLUMN usage_count INT DEFAULT 0 AFTER order_position,
          ADD COLUMN last_used_at TIMESTAMP NULL AFTER usage_count
        `);
        logger.info('✅ Added usage tracking columns to whatsapp_cloud_faqs table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('FAQ usage columns:', e.message);
        }
      }
    }
 
    // Add indexes for better performance
    try {
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_whatsapp_cloud_faqs_keywords ON whatsapp_cloud_faqs(keywords(100))
      `);
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_whatsapp_cloud_faqs_usage ON whatsapp_cloud_faqs(usage_count DESC)
      `);
      logger.info('✅ Added performance indexes to whatsapp_cloud_faqs table');
    } catch (e) {
      logger.warn('FAQ indexes:', e.message);
    }
 
    // Create enhanced FAQ system tables for intelligent processing
    
    // Table for tracking failed searches (for learning purposes)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_faq_failed_searches (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id INT NULL,
        conversation_id INT NULL,
        query TEXT NOT NULL,
        intent VARCHAR(50) NULL,
        search_count INT DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        last_searched_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant_query (tenant_id, query(100)),
        INDEX idx_account_intent (account_id, intent),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_faq_failed_searches table created/verified');
 
    // Table for FAQ performance metrics (for machine learning)
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_faq_metrics (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        faq_id INT NOT NULL,
        total_uses INT DEFAULT 0,
        successful_uses INT DEFAULT 0,
        avg_confidence DECIMAL(4,3) DEFAULT 0.000,
        last_used_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_faq (tenant_id, faq_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (faq_id) REFERENCES whatsapp_cloud_faqs(id) ON DELETE CASCADE,
        INDEX idx_performance (successful_uses, total_uses),
        INDEX idx_confidence (avg_confidence)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_faq_metrics table created/verified');
 
    // Table for user feedback on FAQ responses
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_faq_feedback (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        faq_id INT NOT NULL,
        conversation_id INT NULL,
        user_phone VARCHAR(20) NULL,
        rating TINYINT(1) NULL COMMENT '1=helpful, 0=not helpful',
        feedback_text TEXT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        FOREIGN KEY (faq_id) REFERENCES whatsapp_cloud_faqs(id) ON DELETE CASCADE,
        INDEX idx_tenant_faq (tenant_id, faq_id),
        INDEX idx_rating (rating),
        INDEX idx_created_at (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_faq_feedback table created/verified');
 
    // Table for conversation context tracking
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_conversation_context (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        conversation_id INT NOT NULL,
        user_phone VARCHAR(20) NOT NULL,
        preferred_category VARCHAR(50) NULL,
        interaction_count INT DEFAULT 0,
        last_intent VARCHAR(50) NULL,
        context_data JSON NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_conversation (tenant_id, conversation_id),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_user_phone (user_phone),
        INDEX idx_category (preferred_category)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_conversation_context table created/verified');
 
    // Add enhanced columns to existing FAQ usage table
    const [usageColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_cloud_faq_usage'
    `);
    const existingUsageColumns = usageColumns.map(col => col.COLUMN_NAME);
 
    if (!existingUsageColumns.includes('confidence_score')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_faq_usage 
          ADD COLUMN confidence_score DECIMAL(4,3) NULL AFTER user_message,
          ADD COLUMN intent VARCHAR(50) NULL AFTER confidence_score,
          ADD COLUMN algorithm_used VARCHAR(50) NULL AFTER intent,
          ADD COLUMN context_data JSON NULL AFTER algorithm_used
        `);
        logger.info('✅ Added enhanced tracking columns to whatsapp_cloud_faq_usage table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('FAQ usage enhanced columns:', e.message);
        }
      }
    }
 
    // Add enhanced columns to FAQ settings table
    const [settingsColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_cloud_faq_settings'
    `);
    const existingSettingsColumns = settingsColumns.map(col => col.COLUMN_NAME);
 
    if (!existingSettingsColumns.includes('learning_enabled')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_faq_settings
          ADD COLUMN learning_enabled BOOLEAN DEFAULT TRUE AFTER similarity_threshold,
          ADD COLUMN context_awareness BOOLEAN DEFAULT TRUE AFTER learning_enabled,
          ADD COLUMN feedback_collection BOOLEAN DEFAULT TRUE AFTER context_awareness,
          ADD COLUMN suggestion_threshold DECIMAL(4,3) DEFAULT 0.500 AFTER feedback_collection,
          ADD COLUMN max_suggestions TINYINT(2) DEFAULT 3 AFTER suggestion_threshold
        `);
        logger.info('✅ Added enhanced settings columns to whatsapp_cloud_faq_settings table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('FAQ settings enhanced columns:', e.message);
        }
      }
    }
 
    // Add performance tracking columns to main FAQ table
    if (!existingFaqColumns.includes('performance_score')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_faqs
          ADD COLUMN performance_score DECIMAL(4,3) DEFAULT 0.000 AFTER usage_count,
          ADD COLUMN avg_confidence DECIMAL(4,3) DEFAULT 0.000 AFTER performance_score,
          ADD COLUMN success_rate DECIMAL(4,3) DEFAULT 0.000 AFTER avg_confidence
        `);
        logger.info('✅ Added performance tracking columns to whatsapp_cloud_faqs table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('FAQ performance columns:', e.message);
        }
      }
    }
 
    // Add performance indexes
    try {
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_whatsapp_cloud_faqs_performance ON whatsapp_cloud_faqs(performance_score)
      `);
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_whatsapp_cloud_faqs_success_rate ON whatsapp_cloud_faqs(success_rate)
      `);
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_whatsapp_cloud_faq_usage_confidence ON whatsapp_cloud_faq_usage(confidence_score)
      `);
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_whatsapp_cloud_faq_usage_intent ON whatsapp_cloud_faq_usage(intent)
      `);
      await connection.execute(`
        CREATE INDEX IF NOT EXISTS idx_whatsapp_cloud_faq_usage_algorithm ON whatsapp_cloud_faq_usage(algorithm_used)
      `);
      logger.info('✅ Added enhanced performance indexes');
    } catch (e) {
      logger.warn('Enhanced FAQ indexes:', e.message);
    }
 
    // Create analytics view for FAQ performance
    try {
      await connection.execute(`
        CREATE OR REPLACE VIEW whatsapp_cloud_faq_analytics AS
        SELECT 
            f.id,
            f.tenant_id,
            f.account_id,
            f.question,
            f.category,
            f.active,
            f.usage_count,
            f.performance_score,
            f.avg_confidence,
            f.success_rate,
            f.last_used_at,
            COALESCE(m.total_uses, 0) as metric_total_uses,
            COALESCE(m.successful_uses, 0) as metric_successful_uses,
            COALESCE(fb.helpful_count, 0) as helpful_feedback,
            COALESCE(fb.unhelpful_count, 0) as unhelpful_feedback,
            COALESCE(fb.avg_rating, 0) as avg_user_rating
        FROM whatsapp_cloud_faqs f
        LEFT JOIN whatsapp_cloud_faq_metrics m ON f.id = m.faq_id AND f.tenant_id = m.tenant_id
        LEFT JOIN (
            SELECT 
                faq_id,
                tenant_id,
                SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) as helpful_count,
                SUM(CASE WHEN rating = 0 THEN 1 ELSE 0 END) as unhelpful_count,
                AVG(rating) as avg_rating
            FROM whatsapp_cloud_faq_feedback 
            GROUP BY faq_id, tenant_id
        ) fb ON f.id = fb.faq_id AND f.tenant_id = fb.tenant_id
      `);
      logger.info('✅ Created whatsapp_cloud_faq_analytics view');
    } catch (e) {
      logger.warn('FAQ analytics view:', e.message);
    }
 
    // Insert default enhanced settings for existing tenants without settings
    try {
      await connection.execute(`
        INSERT IGNORE INTO whatsapp_cloud_faq_settings 
        (tenant_id, account_id, auto_reply_enabled, menu_enabled, menu_trigger_keyword, 
         welcome_message, no_match_message, menu_header, menu_footer, similarity_threshold,
         learning_enabled, context_awareness, feedback_collection, suggestion_threshold, max_suggestions)
        SELECT DISTINCT 
            tenant_id, 
            NULL as account_id,
            TRUE as auto_reply_enabled,
            TRUE as menu_enabled,
            'menu' as menu_trigger_keyword,
            'Hello! 👋 How can I help you today?\\n\\nType "menu" to see available options.' as welcome_message,
            'I\\'m sorry, I couldn\\'t find an answer to your question. 🤔\\n\\nPlease contact our support team for assistance, or type "menu" to see available options.' as no_match_message,
            '📋 *Available Options*\\n\\nPlease select an option by typing the corresponding number:' as menu_header,
            '\\n💬 You can also ask me any question directly!' as menu_footer,
            0.70 as similarity_threshold,
            TRUE as learning_enabled,
            TRUE as context_awareness,
            TRUE as feedback_collection,
            0.50 as suggestion_threshold,
            3 as max_suggestions
        FROM whatsapp_cloud_faqs 
        WHERE tenant_id NOT IN (SELECT tenant_id FROM whatsapp_cloud_faq_settings WHERE account_id IS NULL)
      `);
      logger.info('✅ Inserted default enhanced FAQ settings for existing tenants');
    } catch (e) {
      logger.warn('Default FAQ settings:', e.message);
    }
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_flows (
        id INT AUTO_INCREMENT PRIMARY KEY,
        flow_id VARCHAR(64) NOT NULL,
        tenant_id INT NOT NULL,
        account_id VARCHAR(64),
        name VARCHAR(255) NOT NULL,
        description TEXT,
        active BOOLEAN DEFAULT FALSE,
        trigger_type VARCHAR(50),
        trigger_value VARCHAR(255),
        nodes JSON,
        connections JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_flow (tenant_id, flow_id),
        INDEX idx_tenant (tenant_id),
        INDEX idx_account (account_id),
        INDEX idx_active (active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_flows table created/verified');
 
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS whatsapp_cloud_flow_sessions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        account_id VARCHAR(64),
        contact_phone VARCHAR(30) NOT NULL,
        flow_id VARCHAR(64) NOT NULL,
        current_node_id VARCHAR(64),
        waiting_node_id VARCHAR(64),
        waiting_type VARCHAR(32),
        variables JSON,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_session (tenant_id, account_id, contact_phone, flow_id),
        INDEX idx_contact (contact_phone),
        INDEX idx_flow (flow_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ whatsapp_cloud_flow_sessions table created/verified');
 
    // Add stores_can_see_new_conversations column to tenants table
    const [tenantColumnsVisibility] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'tenants'
    `);
    const existingTenantColumnsVisibility = tenantColumnsVisibility.map(col => col.COLUMN_NAME);
 
    if (!existingTenantColumnsVisibility.includes('stores_can_see_new_conversations')) {
      try {
        await connection.execute(`
          ALTER TABLE tenants 
          ADD COLUMN stores_can_see_new_conversations BOOLEAN DEFAULT TRUE 
          COMMENT 'If TRUE, stores can see all new conversations. If FALSE, stores only see conversations after transfer or assignment.'
        `);
        logger.info('✅ Added stores_can_see_new_conversations column to tenants table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('stores_can_see_new_conversations column:', e.message);
        }
      }
    }
 
    // Add transferred_to_store and transferred_to_department columns to whatsapp_cloud_conversations if they don't exist
    const [cloudConvColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_cloud_conversations'
    `);
    const existingCloudConvColumns = cloudConvColumns.map(col => col.COLUMN_NAME);
 
    if (!existingCloudConvColumns.includes('transferred_to_store')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_conversations 
          ADD COLUMN transferred_to_store VARCHAR(100) NULL AFTER department_id
        `);
        logger.info('✅ Added transferred_to_store column to whatsapp_cloud_conversations table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('transferred_to_store column:', e.message);
        }
      }
    }
 
    if (!existingCloudConvColumns.includes('transferred_to_department')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_conversations 
          ADD COLUMN transferred_to_department VARCHAR(100) NULL AFTER transferred_to_store
        `);
        logger.info('✅ Added transferred_to_department column to whatsapp_cloud_conversations table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('transferred_to_department column:', e.message);
        }
      }
    }
 
    if (!existingCloudConvColumns.includes('transferred_at')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_conversations 
          ADD COLUMN transferred_at TIMESTAMP NULL AFTER transferred_to_department
        `);
        logger.info('✅ Added transferred_at column to whatsapp_cloud_conversations table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('transferred_at column:', e.message);
        }
      }
    }
 
    if (!existingCloudConvColumns.includes('transferred_by_user_id')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_cloud_conversations 
          ADD COLUMN transferred_by_user_id INT NULL AFTER transferred_at,
          ADD CONSTRAINT fk_cloud_conv_transferred_by FOREIGN KEY (transferred_by_user_id) REFERENCES users(id) ON DELETE SET NULL
        `);
        logger.info('✅ Added transferred_by_user_id column to whatsapp_cloud_conversations table');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME' && e.code !== 'ER_DUP_KEYNAME') {
          logger.warn('transferred_by_user_id column:', e.message);
        }
      }
    }
 
    // ============================================
    // Evolution API Tables
    // ============================================
 
    // Create evolution_instances table
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS evolution_instances (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tenant_id INT NOT NULL,
        instance_name VARCHAR(100) NOT NULL,
        instance_type ENUM('whatsapp_web', 'whatsapp_business') DEFAULT 'whatsapp_web',
        phone_number VARCHAR(20),
        status ENUM('disconnected', 'connecting', 'qr_code', 'connected', 'error') DEFAULT 'disconnected',
        qr_code TEXT,
        evolution_instance_id VARCHAR(255),
        evolution_api_key VARCHAR(255),
        webhook_url VARCHAR(500),
        webhook_events JSON,
        connection_data JSON,
        profile_picture_url VARCHAR(500),
        profile_name VARCHAR(255),
        last_connected_at TIMESTAMP NULL,
        error_message TEXT,
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_tenant_instance (tenant_id, instance_name),
        FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
        INDEX idx_tenant (tenant_id),
        INDEX idx_status (status),
        INDEX idx_evolution_instance (evolution_instance_id),
        INDEX idx_active (is_active)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
    logger.info('✅ evolution_instances table created/verified');
 
    // Add profile picture columns if they don't exist
    const [evolutionColumns] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'evolution_instances'
    `);
    const existingEvolutionColumns = evolutionColumns.map(col => col.COLUMN_NAME);
 
    if (!existingEvolutionColumns.includes('profile_picture_url')) {
      try {
        await connection.execute(`
          ALTER TABLE evolution_instances 
          ADD COLUMN profile_picture_url VARCHAR(500) AFTER connection_data
        `);
        logger.info('✅ Added profile_picture_url to evolution_instances');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('profile_picture_url column:', e.message);
        }
      }
    }
 
    if (!existingEvolutionColumns.includes('profile_name')) {
      try {
        await connection.execute(`
          ALTER TABLE evolution_instances 
          ADD COLUMN profile_name VARCHAR(255) AFTER profile_picture_url
        `);
        logger.info('✅ Added profile_name to evolution_instances');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('profile_name column:', e.message);
        }
      }
    }
 
    // Now that evolution_instances table exists, add foreign key and unique constraint to ai_configurations
    try {
      // Check if foreign key already exists
      const [fkExists] = await connection.query(`
        SELECT CONSTRAINT_NAME 
        FROM information_schema.TABLE_CONSTRAINTS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'ai_configurations' 
          AND CONSTRAINT_NAME = 'fk_ai_config_evolution_instance'
      `);
      
      if (fkExists.length === 0) {
        await connection.execute(`
          ALTER TABLE ai_configurations 
          ADD CONSTRAINT fk_ai_config_evolution_instance 
          FOREIGN KEY (evolution_instance_id) REFERENCES evolution_instances(id) ON DELETE CASCADE
        `);
        logger.info('✅ Added foreign key constraint to ai_configurations.evolution_instance_id');
      }
    } catch (e) {
      logger.warn('ai_configurations foreign key:', e.message);
    }
 
    // Add unique constraint for tenant_id + evolution_instance_id if not exists
    try {
      const [uniqueExists] = await connection.query(`
        SELECT CONSTRAINT_NAME 
        FROM information_schema.TABLE_CONSTRAINTS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'ai_configurations' 
          AND CONSTRAINT_NAME = 'unique_tenant_instance'
      `);
      
      if (uniqueExists.length === 0) {
        await connection.execute(`
          ALTER TABLE ai_configurations 
          ADD UNIQUE KEY unique_tenant_instance (tenant_id, evolution_instance_id)
        `);
        logger.info('✅ Added unique constraint for tenant_id + evolution_instance_id');
      }
    } catch (e) {
      logger.warn('unique_tenant_instance constraint:', e.message);
    }
 
    // Add foreign keys to mass_send tables
    try {
      const [fkHistoryExists] = await connection.query(`
        SELECT CONSTRAINT_NAME 
        FROM information_schema.TABLE_CONSTRAINTS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'mass_send_history' 
          AND CONSTRAINT_NAME = 'fk_mass_send_history_evolution_instance'
      `);
      
      if (fkHistoryExists.length === 0) {
        await connection.execute(`
          ALTER TABLE mass_send_history 
          ADD CONSTRAINT fk_mass_send_history_evolution_instance 
          FOREIGN KEY (evolution_instance_id) REFERENCES evolution_instances(id) ON DELETE SET NULL
        `);
        logger.info('✅ Added foreign key constraint to mass_send_history.evolution_instance_id');
      }
    } catch (e) {
      logger.warn('mass_send_history foreign key:', e.message);
    }
 
    try {
      const [fkSchedulesExists] = await connection.query(`
        SELECT CONSTRAINT_NAME 
        FROM information_schema.TABLE_CONSTRAINTS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'mass_send_schedules' 
          AND CONSTRAINT_NAME = 'fk_mass_send_schedules_evolution_instance'
      `);
      
      if (fkSchedulesExists.length === 0) {
        await connection.execute(`
          ALTER TABLE mass_send_schedules 
          ADD CONSTRAINT fk_mass_send_schedules_evolution_instance 
          FOREIGN KEY (evolution_instance_id) REFERENCES evolution_instances(id) ON DELETE SET NULL
        `);
        logger.info('✅ Added foreign key constraint to mass_send_schedules.evolution_instance_id');
      }
    } catch (e) {
      logger.warn('mass_send_schedules foreign key:', e.message);
    }
 
    try {
      const [fkRemindersExists] = await connection.query(`
        SELECT CONSTRAINT_NAME 
        FROM information_schema.TABLE_CONSTRAINTS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'mass_send_reminders' 
          AND CONSTRAINT_NAME = 'fk_mass_send_reminders_evolution_instance'
      `);
      
      if (fkRemindersExists.length === 0) {
        await connection.execute(`
          ALTER TABLE mass_send_reminders 
          ADD CONSTRAINT fk_mass_send_reminders_evolution_instance 
          FOREIGN KEY (evolution_instance_id) REFERENCES evolution_instances(id) ON DELETE SET NULL
        `);
        logger.info('✅ Added foreign key constraint to mass_send_reminders.evolution_instance_id');
      }
    } catch (e) {
      logger.warn('mass_send_reminders foreign key:', e.message);
    }
 
    // Add max_whatsapp_instances to subscription_plans
    const [planColumnsEvolution] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'subscription_plans'
    `);
    const existingPlanColumnsEvolution = planColumnsEvolution.map(col => col.COLUMN_NAME);
 
    if (!existingPlanColumnsEvolution.includes('max_whatsapp_instances')) {
      try {
        await connection.execute(`
          ALTER TABLE subscription_plans 
          ADD COLUMN max_whatsapp_instances INT DEFAULT 1 AFTER max_devices
        `);
        logger.info('✅ Added max_whatsapp_instances to subscription_plans');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('max_whatsapp_instances column:', e.message);
        }
      }
    }
 
    // Add max_whatsapp_instances to tenants
    const [tenantColumnsEvolution] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'tenants'
    `);
    const existingTenantColumnsEvolution = tenantColumnsEvolution.map(col => col.COLUMN_NAME);
 
    if (!existingTenantColumnsEvolution.includes('max_whatsapp_instances')) {
      try {
        await connection.execute(`
          ALTER TABLE tenants 
          ADD COLUMN max_whatsapp_instances INT DEFAULT 1 AFTER max_devices
        `);
        logger.info('✅ Added max_whatsapp_instances to tenants');
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('max_whatsapp_instances column:', e.message);
        }
      }
    }
 
    // Sync max_whatsapp_instances from plans to tenants (auto-sync on server restart)
    try {
      logger.info('🔄 Syncing max_whatsapp_instances from plans to tenants...');
      const [syncResult] = await connection.execute(`
        UPDATE tenants t
        INNER JOIN subscription_plans sp ON t.plan_id = sp.id
        SET t.max_whatsapp_instances = COALESCE(sp.max_whatsapp_instances, 1)
        WHERE t.id != 0 AND (t.max_whatsapp_instances IS NULL OR t.max_whatsapp_instances != sp.max_whatsapp_instances)
      `);
      
      if (syncResult.affectedRows > 0) {
        logger.info(`✅ Synced max_whatsapp_instances for ${syncResult.affectedRows} tenant(s)`);
      } else {
        logger.info('✅ All tenants already have correct max_whatsapp_instances');
      }
    } catch (syncError) {
      logger.warn('Could not sync max_whatsapp_instances:', syncError.message);
      // Don't fail initialization if sync fails
    }
 
    // Sync ALL plan limits to tenants (comprehensive auto-sync on server restart)
    try {
      logger.info('🔄 Syncing all plan limits to tenants...');
      const [fullSyncResult] = await connection.execute(`
        UPDATE tenants t
        INNER JOIN subscription_plans sp ON t.plan_id = sp.id
        SET 
          t.max_stores = COALESCE(sp.max_stores, 1),
          t.max_users = COALESCE(sp.max_users, 5),
          t.max_departments = COALESCE(sp.max_departments, 5),
          t.max_contacts = COALESCE(sp.max_contacts, 1000),
          t.max_devices = COALESCE(sp.max_devices, 1),
          t.max_whatsapp_instances = COALESCE(sp.max_whatsapp_instances, 1),
          t.max_conversations = COALESCE(sp.max_conversations, 1000),
          t.max_messages_per_month = COALESCE(sp.max_messages_per_month, 10000),
          t.max_faqs = COALESCE(sp.max_faqs, 10),
          t.max_contact_groups = COALESCE(sp.max_contact_groups, 10),
          t.max_widgets = COALESCE(sp.max_widgets, 0),
          t.max_invoices_per_month = COALESCE(sp.max_invoices_per_month, 0),
          t.max_quotes_per_month = COALESCE(sp.max_quotes_per_month, 0),
          t.max_payment_links_per_month = COALESCE(sp.max_payment_links_per_month, 0),
          t.max_email_accounts = COALESCE(sp.max_email_accounts, 0),
          t.max_emails_per_month = COALESCE(sp.max_emails_per_month, 0),
          t.max_omnichannel_accounts = COALESCE(sp.max_omnichannel_accounts, 0)
        WHERE t.id != 0 AND t.plan_id IS NOT NULL
      `);
      
      if (fullSyncResult.affectedRows > 0) {
        logger.info(`✅ Synced all plan limits for ${fullSyncResult.affectedRows} tenant(s)`);
      } else {
        logger.info('✅ All tenants already have correct plan limits');
      }
    } catch (fullSyncError) {
      logger.warn('Could not sync all plan limits:', fullSyncError.message);
      // Don't fail initialization if sync fails
    }
 
    // Add instance_id to whatsapp_messages
    const [messageColumnsEvolution] = await connection.query(`
      SELECT COLUMN_NAME 
      FROM information_schema.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'whatsapp_messages'
    `);
    const existingMessageColumnsEvolution = messageColumnsEvolution.map(col => col.COLUMN_NAME);
 
    if (!existingMessageColumnsEvolution.includes('instance_id')) {
      try {
        await connection.execute(`
          ALTER TABLE whatsapp_messages 
          ADD COLUMN instance_id INT NULL AFTER tenant_id
        `);
        logger.info('✅ Added instance_id to whatsapp_messages');
        
        // Add foreign key constraint
        try {
          await connection.execute(`
            ALTER TABLE whatsapp_messages 
            ADD CONSTRAINT fk_messages_instance 
            FOREIGN KEY (instance_id) REFERENCES evolution_instances(id) ON DELETE SET NULL
          `);
          logger.info('✅ Added foreign key constraint for instance_id');
        } catch (fkError) {
          if (fkError.code !== 'ER_DUP_KEYNAME' && fkError.code !== 'ER_FK_DUP_NAME') {
            logger.warn('instance_id FK:', fkError.message);
          }
        }
      } catch (e) {
        if (e.code !== 'ER_DUP_FIELDNAME') {
          logger.warn('instance_id column:', e.message);
        }
      }
    }
 
    logger.info('✅ Database initialization completed successfully');
    } catch (innerError) {
      logger.error('❌ Error during database initialization', { 
        error: innerError.message,
        sql: innerError.sql,
        code: innerError.code,
        stack: innerError.stack
      });
      throw innerError;
    }
    
    connection.release();
  } catch (error) {
    if (connection) connection.release();
    logger.error('❌ Database initialization failed', { error: error.message });
    throw error;
  }
}
 
module.exports = {
  pool,
  initDatabase,
  testConnection
};