All files / services api.ts

0% Statements 0/686
0% Branches 0/493
0% Functions 0/74
0% Lines 0/661

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import type { ApiError, ApiResponse, AuthResponse, Beneficiary, BeneficiaryDashboardData, ChatResponse, DashboardSingleResponse, NotificationHistoryResponse, NotificationSettings, WPSensor } from '@/types';
import { File } from 'expo-file-system';
import * as SecureStore from 'expo-secure-store';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as wifiPasswordStore from './wifiPasswordStore';
import 'react-native-get-random-values'; // Polyfill for crypto.getRandomValues
import { bustImageCache } from '@/utils/imageUtils';
 
// Callback for handling unauthorized responses (401)
let onUnauthorizedCallback: (() => void) | null = null;
 
export function setOnUnauthorizedCallback(callback: () => void) {
  onUnauthorizedCallback = callback;
}
 
// Callback for BLE cleanup on logout
let onLogoutBLECleanupCallback: (() => Promise<void>) | null = null;
 
export function setOnLogoutBLECleanupCallback(callback: (() => Promise<void>) | null) {
  onLogoutBLECleanupCallback = callback;
}
 
const API_BASE_URL = 'https://eluxnetworks.net/function/well-api/api';
const CLIENT_ID = 'MA_001';
 
// Threshold for considering a beneficiary "online" (30 minutes in milliseconds)
const ONLINE_THRESHOLD_MS = 30 * 60 * 1000;
 
// WellNuo Backend API (our own API for auth, OTP, etc.)
// TODO: Update to production URL when deployed
const WELLNUO_API_URL = 'https://wellnuo.smartlaunchhub.com/api';
 
// Avatar images for elderly beneficiaries - grandmothers (бабушки)
const ELDERLY_AVATARS = [
  'https://images.unsplash.com/photo-1566616213894-2d4e1baee5d8?w=200&h=200&fit=crop&crop=face', // grandmother with gray hair
  'https://images.unsplash.com/photo-1544027993-37dbfe43562a?w=200&h=200&fit=crop&crop=face', // elderly woman smiling
  'https://images.unsplash.com/photo-1491308056676-205b7c9a7dc1?w=200&h=200&fit=crop&crop=face', // senior woman portrait
  'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=200&h=200&fit=crop&crop=face', // older woman glasses
  'https://images.unsplash.com/photo-1548142813-c348350df52b?w=200&h=200&fit=crop&crop=face', // grandmother portrait
];
 
// Room locations for sensor placement
// Used in device settings to select where sensor is installed
export const ROOM_LOCATIONS = [
  { id: 'bedroom', label: 'Bedroom', icon: '🛏️', legacyCode: 102 },
  { id: 'living_room', label: 'Living Room', icon: '🛋️', legacyCode: 103 },
  { id: 'kitchen', label: 'Kitchen', icon: '🍳', legacyCode: 104 },
  { id: 'bathroom', label: 'Bathroom', icon: '🚿', legacyCode: 105 },
  { id: 'hallway', label: 'Hallway', icon: '🚪', legacyCode: 106 },
  { id: 'entrance', label: 'Entrance', icon: '🏠', legacyCode: 111 },
  { id: 'garage', label: 'Garage', icon: '🚗', legacyCode: 108 },
  { id: 'basement', label: 'Basement', icon: '🪜', legacyCode: 110 },
  { id: 'office', label: 'Office', icon: '💼', legacyCode: 107 },
  { id: 'other', label: 'Other', icon: '📍', legacyCode: 200 },
] as const;
 
export type RoomLocationId = typeof ROOM_LOCATIONS[number]['id'];
 
// Helper to convert location ID to Legacy API code
function getLocationLegacyCode(locationId: string): number | undefined {
  const location = ROOM_LOCATIONS.find(loc => loc.id === locationId);
  return location?.legacyCode;
}
 
// Helper to convert Legacy API code to location ID
export function getLocationIdFromCode(code: number): RoomLocationId | undefined {
  const location = ROOM_LOCATIONS.find(loc => loc.legacyCode === code);
  return location?.id;
}
 
// Helper to convert location label (e.g., "Kitchen") to location ID (e.g., "kitchen")
// Legacy API sometimes returns label instead of code
export function getLocationIdFromLabel(label: string): RoomLocationId | undefined {
  // Case-insensitive comparison
  const labelLower = label.toLowerCase().trim();
  const location = ROOM_LOCATIONS.find(loc => loc.label.toLowerCase() === labelLower);
  return location?.id;
}
 
// Get consistent avatar based on deployment_id
function getAvatarForBeneficiary(deploymentId: number): string {
  const index = deploymentId % ELDERLY_AVATARS.length;
  return ELDERLY_AVATARS[index];
}
 
// Helper function to format time ago
function formatTimeAgo(date: Date): string {
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHours / 24);
 
  if (diffMins < 1) return 'Just now';
  if (diffMins < 60) return `${diffMins} min ago`;
  if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
  return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
}
 
class ApiService {
  // API URLs as instance properties for consistency
  private readonly baseUrl = WELLNUO_API_URL;
  private readonly legacyApiUrl = API_BASE_URL;
 
  // Public method to get the access token (used by AuthContext)
  async getToken(): Promise<string | null> {
    try {
      return await SecureStore.getItemAsync('accessToken');
    } catch {
      return null;
    }
  }
 
  // Get legacy API token (for eluxnetworks.net API - dashboard, voice_ask)
  private async getLegacyToken(): Promise<string | null> {
    try {
      return await SecureStore.getItemAsync('legacyAccessToken');
    } catch {
      return null;
    }
  }
 
  private generateNonce(): string {
    // Use Web Crypto API (polyfilled by react-native-get-random-values)
    const randomBytes = new Uint8Array(16);
    crypto.getRandomValues(randomBytes);
    return Array.from(randomBytes)
      .map(b => b.toString(16).padStart(2, '0'))
      .join('');
  }
 
  private async makeRequest<T>(params: Record<string, string>): Promise<ApiResponse<T>> {
    try {
      const formData = new URLSearchParams();
      Object.entries(params).forEach(([key, value]) => {
        formData.append(key, value);
      });
 
      const response = await fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData.toString(),
      });
 
      const data = await response.json();
 
      // Handle 401 Unauthorized - trigger logout
      if (response.status === 401 || data.status === '401' || data.error === 'Unauthorized') {
        if (onUnauthorizedCallback) {
          onUnauthorizedCallback();
        }
        return {
          ok: false,
          error: {
            message: 'Session expired. Please login again.',
            code: 'UNAUTHORIZED',
            status: 401,
          },
        };
      }
 
      if (data.status === '200 OK' || data.ok === true) {
        return { data: data as T, ok: true };
      }
 
      return {
        ok: false,
        error: {
          message: data.message || data.error || 'Request failed',
          status: response.status,
        },
      };
    } catch (error) {
      const apiError: ApiError = {
        message: error instanceof Error ? error.message : 'Network error',
        code: 'NETWORK_ERROR',
      };
      return { ok: false, error: apiError };
    }
  }
 
  // Authentication (Legacy API - eluxnetworks.net)
  // Used for dev mode and dashboard access
  async login(username: string, password: string): Promise<ApiResponse<AuthResponse>> {
    const response = await this.makeRequest<AuthResponse>({
      function: 'credentials',
      email: username,
      ps: password,
      clientId: CLIENT_ID,
      nonce: this.generateNonce(),
    });
 
    if (response.ok && response.data) {
      // Save LEGACY credentials separately (not to accessToken!)
      // accessToken is reserved for WellNuo API JWT tokens
      await SecureStore.setItemAsync('legacyAccessToken', response.data.access_token);
      // Keep these for backward compatibility
      await SecureStore.setItemAsync('userId', response.data.user_id.toString());
      await SecureStore.setItemAsync('privileges', response.data.privileges);
      await SecureStore.setItemAsync('maxRole', response.data.max_role.toString());
    }
 
    return response;
  }
 
  async logout(): Promise<void> {
    // Call BLE cleanup callback if set
    if (onLogoutBLECleanupCallback) {
      try {
        await onLogoutBLECleanupCallback();
      } catch (error) {
        // Continue with logout even if BLE cleanup fails
      }
    }
 
    // Clear WiFi passwords and encryption key from SecureStore
    try {
      await wifiPasswordStore.clearAllWiFiPasswords();
    } catch (error) {
      // Continue with logout even if cleanup fails
    }
 
    // Clear encryption key
    try {
      const { clearEncryptionKey } = await import('./encryption');
      await clearEncryptionKey();
    } catch (error) {
      // Continue with logout even if cleanup fails
    }
 
    // Clear WellNuo API auth data
    await SecureStore.deleteItemAsync('accessToken');
    await SecureStore.deleteItemAsync('userId');
    await SecureStore.deleteItemAsync('userEmail');
    await SecureStore.deleteItemAsync('onboardingCompleted');
    // Clear legacy API auth data
    await SecureStore.deleteItemAsync('legacyAccessToken');
    await SecureStore.deleteItemAsync('privileges');
    await SecureStore.deleteItemAsync('maxRole');
    // Clear user profile data (avatar, etc.)
    await SecureStore.deleteItemAsync('userAvatar');
    // Clear local cached data (beneficiaries, etc.)
    await AsyncStorage.removeItem('wellnuo_local_beneficiaries');
  }
 
  // Save user email (for OTP auth flow)
  async saveEmail(email: string): Promise<void> {
    await SecureStore.setItemAsync('userEmail', email);
  }
 
  // Get stored email
  async getStoredEmail(): Promise<string | null> {
    try {
      return await SecureStore.getItemAsync('userEmail');
    } catch {
      return null;
    }
  }
 
  // Onboarding completion flag - persists across app restarts
  async setOnboardingCompleted(completed: boolean): Promise<void> {
    await SecureStore.setItemAsync('onboardingCompleted', completed ? '1' : '0');
  }
 
  async isOnboardingCompleted(): Promise<boolean> {
    try {
      const value = await SecureStore.getItemAsync('onboardingCompleted');
      return value === '1';
    } catch {
      return false;
    }
  }
 
  // Save mock user (for dev mode OTP flow)
  async saveMockUser(user: { user_id: string; email: string; max_role: string; privileges: string[] }): Promise<void> {
    await SecureStore.setItemAsync('accessToken', `mock-token-${user.user_id}`);
    await SecureStore.setItemAsync('userId', user.user_id);
    await SecureStore.setItemAsync('privileges', user.privileges.join(','));
    await SecureStore.setItemAsync('maxRole', user.max_role);
    await SecureStore.setItemAsync('userEmail', user.email);
  }
 
  // ==================== OTP Authentication (WellNuo Backend) ====================
 
  // Check if email exists in database
  async checkEmail(email: string): Promise<ApiResponse<{ exists: boolean; name?: string | null }>> {
    try {
      const response = await fetch(`${WELLNUO_API_URL}/auth/check-email`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to check email' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Request OTP code - sends email via Brevo
  async requestOTP(email: string): Promise<ApiResponse<{ message: string }>> {
    try {
      const response = await fetch(`${WELLNUO_API_URL}/auth/request-otp`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to send OTP' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Verify OTP code and get JWT token
  async verifyOTP(email: string, code: string): Promise<ApiResponse<{ token: string; user: { id: string; email: string; first_name?: string; last_name?: string } }>> {
    try {
      const payload = { email: email.trim().toLowerCase(), code };
 
      const response = await fetch(`${WELLNUO_API_URL}/auth/verify-otp`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });
 
      const data = await response.json();
 
      if (response.ok && data.token) {
        // Save ONLY technical auth data (token, userId, email)
        // User profile data is fetched from API, NOT stored locally
        await SecureStore.setItemAsync('accessToken', data.token);
        await SecureStore.setItemAsync('userId', String(data.user.id));
        await SecureStore.setItemAsync('userEmail', email);
 
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || data.message || 'Invalid or expired code' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  async isAuthenticated(): Promise<boolean> {
    const token = await this.getToken();
    return !!token;
  }
 
  // Get current user profile from API (not local storage!)
  async getStoredUser() {
    try {
      const token = await this.getToken();
      const userId = await SecureStore.getItemAsync('userId');
 
      if (!token || !userId) {
        return null;
      }
 
      // Fetch profile from server
      const profile = await this.getProfile();
 
      if (!profile.ok || !profile.data) {
        // If token is invalid (401), clear all tokens and return null
        // This will trigger re-authentication
        if (profile.error?.code === 'UNAUTHORIZED') {
          await this.logout();
          return null;
        }
 
        // For network errors OR other API errors, fall back to minimal info
        // We don't want to log out the user just because the server is temporarily unavailable
        const email = await SecureStore.getItemAsync('userEmail');
        return {
          user_id: parseInt(userId, 10),
          email: email || undefined,
          privileges: '',
          max_role: 0,
        };
      }
 
      // /auth/me returns { user: {...}, beneficiaries: [...] }
      // Extract user data from nested 'user' object
      const userData = profile.data.user || profile.data;
 
      return {
        user_id: userData.id,
        email: userData.email,
        firstName: userData.firstName,
        lastName: userData.lastName,
        phone: userData.phone,
        privileges: '',
        max_role: 0,
      };
    } catch (error) {
      // On any unexpected error, fall back to local data instead of logging out
      const userId = await SecureStore.getItemAsync('userId');
      const email = await SecureStore.getItemAsync('userEmail');
      if (userId) {
        return {
          user_id: parseInt(userId, 10),
          email: email || undefined,
          privileges: '',
          max_role: 0,
        };
      }
      return null;
    }
  }
 
  // Get user profile from WellNuo API
  // Note: /auth/me can return { user: {...}, beneficiaries: [...] } or just { id, email, ... }
  async getProfile(): Promise<ApiResponse<{
    id: number;
    email: string;
    firstName: string | null;
    lastName: string | null;
    phone: string | null;
    address: {
      street: string | null;
      city: string | null;
      zip: string | null;
      state: string | null;
      country: string | null;
    };
    createdAt: string;
    user?: {
      id: number;
      email: string;
      firstName: string | null;
      lastName: string | null;
      phone: string | null;
    };
  }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/auth/me`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return {
          ok: false,
          error: {
            message: data.error || 'Failed to get profile',
            code: response.status === 401 ? 'UNAUTHORIZED' : 'API_ERROR',
          }
        };
      }
 
      return { data, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Update user profile on WellNuo API
  async updateProfile(updates: {
    firstName?: string;
    lastName?: string;
    phone?: string;
    address?: {
      street?: string;
      city?: string;
      zip?: string;
      state?: string;
      country?: string;
    };
  }): Promise<ApiResponse<{ id: number; email: string; firstName: string | null; lastName: string | null; phone: string | null }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/auth/profile`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updates),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: data.error || 'Failed to update profile' } };
      }
 
      return { data, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Update user profile avatar on WellNuo API
  async updateProfileAvatar(imageUri: string | null): Promise<ApiResponse<{ id: string; avatarUrl: string | null }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      let avatarData: string | null = null;
 
      if (imageUri) {
        // Read image as base64 using new expo-file-system v19+ File API
        const file = new File(imageUri);
        const base64Data = await file.base64();
 
        // Determine MIME type from URI
        const extension = imageUri.split('.').pop()?.toLowerCase() || 'jpeg';
        const mimeType = extension === 'png' ? 'image/png' : 'image/jpeg';
 
        avatarData = `data:${mimeType};base64,${base64Data}`;
      }
 
      const response = await fetch(`${WELLNUO_API_URL}/auth/avatar`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ avatar: avatarData }),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: data.error || 'Failed to update avatar' } };
      }
 
      return { data: data.user, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Beneficiaries (elderly people being monitored)
  async getBeneficiaries(): Promise<ApiResponse<{ beneficiaries: Beneficiary[] }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    // Note: Using mock data since API structure is not fully documented
    // Replace with actual API call when available
    const mockBeneficiaries: Beneficiary[] = [
      {
        id: 1,
        name: 'Julia Smith',
        displayName: 'Julia Smith',
        status: 'online',
        relationship: 'Mother',
        last_activity: '2 min ago',
        sensor_data: {
          motion_detected: true,
          last_motion: '2 min ago',
          door_status: 'closed',
          temperature: 22,
          humidity: 45,
        },
      },
      {
        id: 2,
        name: 'Robert Johnson',
        displayName: 'Robert Johnson',
        status: 'offline',
        relationship: 'Father',
        last_activity: '1 hour ago',
        sensor_data: {
          motion_detected: false,
          last_motion: '1 hour ago',
          door_status: 'closed',
          temperature: 21,
          humidity: 50,
        },
      },
    ];
 
    return { data: { beneficiaries: mockBeneficiaries }, ok: true };
  }
 
  async getBeneficiary(id: number): Promise<ApiResponse<Beneficiary>> {
    // Use real API data via getBeneficiaryDashboard
    const response = await this.getBeneficiaryDashboard(id.toString());
 
    if (!response.ok || !response.data) {
      return { ok: false, error: response.error || { message: 'Beneficiary not found', code: 'NOT_FOUND' } };
    }
 
    const data = response.data;
    // Determine if beneficiary is "online" based on last_detected_time
    const lastDetected = data.last_detected_time ? new Date(data.last_detected_time) : null;
    const isRecent = lastDetected && (Date.now() - lastDetected.getTime()) < ONLINE_THRESHOLD_MS;
 
    const deploymentId = parseInt(data.deployment_id, 10);
    const beneficiary: Beneficiary = {
      id: deploymentId,
      name: data.name,
      displayName: data.name, // For UI display
      avatar: getAvatarForBeneficiary(deploymentId),
      status: isRecent ? 'online' : 'offline',
      address: data.address,
      timezone: data.time_zone,
      wellness_score: data.wellness_score_percent,
      wellness_descriptor: data.wellness_descriptor,
      last_location: data.last_location,
      temperature: data.temperature,
      units: data.units,
      sleep_hours: data.sleep_hours,
      bedroom_temperature: data.bedroom_temperature,
      before_last_location: data.before_last_location,
      last_detected_time: data.last_detected_time,
      last_activity: data.last_detected_time
        ? formatTimeAgo(new Date(data.last_detected_time))
        : undefined,
    };
 
    return { data: beneficiary, ok: true };
  }
 
  // Get beneficiary dashboard data by deployment_id (LEGACY API - eluxnetworks.net)
  async getBeneficiaryDashboard(deploymentId: string): Promise<ApiResponse<BeneficiaryDashboardData>> {
    // Use legacy API credentials for dashboard
    const token = await this.getLegacyToken();
 
    if (!token) {
      // Fallback to regular credentials if legacy not available
      const fallbackToken = await this.getToken();
      if (!fallbackToken) {
        return { ok: false, error: { message: 'Not authenticated for dashboard access', code: 'UNAUTHORIZED' } };
      }
      // Note: This will likely fail if using WellNuo token, but we try anyway
    }
 
    const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
 
    const response = await this.makeRequest<DashboardSingleResponse>({
      function: 'dashboard_single',
      token: token || await this.getToken() || '',
      deployment_id: deploymentId,
      date: today,
      nonce: this.generateNonce(),
    });
 
    if (response.ok && response.data?.result_list?.[0]) {
      return { data: response.data.result_list[0], ok: true };
    }
 
    return {
      ok: false,
      error: response.error || { message: 'Failed to get beneficiary data' },
    };
  }
 
  // Get all beneficiaries from WellNuo API
  async getAllBeneficiaries(): Promise<ApiResponse<Beneficiary[]>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        if (response.status === 401) {
          if (onUnauthorizedCallback) onUnauthorizedCallback();
          return { ok: false, error: { message: 'Session expired', code: 'UNAUTHORIZED', status: 401 } };
        }
        return { ok: false, error: { message: data.error || 'Failed to get beneficiaries' } };
      }
 
      // Map API response to Beneficiary type
      const beneficiaries: Beneficiary[] = (data.beneficiaries || []).map((item: any) => ({
        id: item.id,
        name: item.originalName || item.name || item.email, // Original name from server
        customName: item.customName || null, // User's custom name for this beneficiary
        displayName: item.displayName || item.customName || item.name || item.email || 'Unknown User', // Server-provided displayName
        originalName: item.originalName || item.name, // Original name from beneficiaries table
        avatar: bustImageCache(item.avatarUrl) || undefined, // Use uploaded avatar from server with cache-busting
        status: 'offline' as const,
        email: item.email,
        address: typeof item.address === 'string' ? item.address : (item.address?.street ? `${item.address.street}, ${item.address.city}` : undefined),
        subscription: item.subscription,
        // Equipment status from orders
        equipmentStatus: item.equipmentStatus,
        hasDevices: item.hasDevices || false,
        trackingNumber: item.trackingNumber,
        role: item.role, // User's role for this beneficiary (custodian, guardian, caretaker)
      }));
 
      return { data: beneficiaries, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Get single beneficiary details from WellNuo API
  async getWellNuoBeneficiary(id: number): Promise<ApiResponse<Beneficiary>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries/${id}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: data.error || 'Failed to get beneficiary' } };
      }
 
      const beneficiary: Beneficiary = {
        id: data.id,
        name: data.originalName || data.name || data.email, // Original name from server
        customName: data.customName || null, // User's custom name for this beneficiary
        displayName: data.displayName || data.customName || data.name || data.email || 'Unknown User', // Server-provided displayName
        originalName: data.originalName || data.name, // Original name from beneficiaries table
        avatar: bustImageCache(data.avatarUrl) || undefined, // Cache-bust avatar URL
        status: 'offline' as const,
        email: data.email,
        address: typeof data.address === 'string' ? data.address : (data.address?.street ? `${data.address.street}, ${data.address.city}` : undefined),
        subscription: data.subscription ? {
          status: data.subscription.status,
          planType: data.subscription.planType || data.subscription.plan,
          endDate: data.subscription.endDate,
          cancelAtPeriodEnd: data.subscription.cancelAtPeriodEnd,
        } : undefined,
        // Equipment status from orders
        equipmentStatus: data.equipmentStatus,
        hasDevices: data.hasDevices || false,
        trackingNumber: data.trackingNumber,
        // User's role for this beneficiary (custodian, guardian, caretaker)
        role: data.role,
      };
 
      return { data: beneficiary, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Update beneficiary in WellNuo API
  async updateWellNuoBeneficiary(id: number, updates: {
    name?: string;
    phone?: string;
    address?: string;
  }): Promise<ApiResponse<Beneficiary>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries/${id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(updates),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: data.error || 'Failed to update beneficiary' } };
      }
 
      const beneficiary: Beneficiary = {
        id: data.beneficiary.id,
        name: data.beneficiary.name || data.beneficiary.email,
        displayName: data.beneficiary.displayName || data.beneficiary.name || data.beneficiary.email || 'Unknown User',
        email: data.beneficiary.email,
        status: 'offline' as const,
      };
 
      return { data: beneficiary, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Create new beneficiary (grants owner access automatically)
  async createBeneficiary(data: {
    name: string;
    phone?: string;
    address?: string;
  }): Promise<ApiResponse<Beneficiary>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(data),
      });
 
      const result = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: result.error || 'Failed to create beneficiary' } };
      }
 
      const beneficiary: Beneficiary = {
        id: result.beneficiary.id,
        name: result.beneficiary.name || '',
        displayName: result.beneficiary.name || 'Unknown User', // For UI display
        status: 'offline' as const,
      };
 
      return { data: beneficiary, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Upload/update beneficiary avatar
  async updateBeneficiaryAvatar(id: number, imageUri: string | null): Promise<ApiResponse<{ avatarUrl: string | null }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      let base64Image: string | null = null;
 
      if (imageUri) {
        // Read file as base64 using new expo-file-system v19+ File API
        const file = new File(imageUri);
        const base64Data = await file.base64();
 
        // Determine mime type from URI extension
        const extension = imageUri.split('.').pop()?.toLowerCase() || 'jpeg';
        const mimeType = extension === 'png' ? 'image/png' : 'image/jpeg';
 
        // Create data URI
        base64Image = `data:${mimeType};base64,${base64Data}`;
 
      }
 
      const apiResponse = await fetch(`${WELLNUO_API_URL}/me/beneficiaries/${id}/avatar`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ avatar: base64Image }),
      });
 
      const data = await apiResponse.json();
 
      if (!apiResponse.ok) {
        return { ok: false, error: { message: data.error || 'Failed to update avatar' } };
      }
 
      return { data: { avatarUrl: data.beneficiary?.avatarUrl || null }, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Delete beneficiary (removes access record)
  async deleteBeneficiary(id: number): Promise<ApiResponse<{ success: boolean }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: data.error || 'Failed to delete beneficiary' } };
      }
 
      return { data: { success: true }, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Update beneficiary equipment status
  async updateBeneficiaryEquipmentStatus(
    id: number,
    status: 'none' | 'ordered' | 'shipped' | 'delivered'
  ): Promise<ApiResponse<{ success: boolean }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries/${id}/equipment-status`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ status }),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: data.error || 'Failed to update equipment status' } };
      }
 
      return { data: { success: true }, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // Update beneficiary custom name (per-user, stored in user_access)
  async updateBeneficiaryCustomName(
    id: number,
    customName: string | null
  ): Promise<ApiResponse<{ customName: string | null }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries/${id}/custom-name`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ customName }),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return { ok: false, error: { message: data.error || 'Failed to update custom name' } };
      }
 
      return { data: { customName: data.customName }, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  // AI Chat - deploymentId is required, no default value for security (LEGACY API)
  async sendMessage(question: string, deploymentId: string): Promise<ApiResponse<ChatResponse>> {
    if (!deploymentId) {
      return { ok: false, error: { message: 'Please select a beneficiary first', code: 'NO_BENEFICIARY_SELECTED' } };
    }
    // Use legacy API credentials for voice_ask
    const token = await this.getLegacyToken() || await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    return this.makeRequest<ChatResponse>({
      function: 'voice_ask',
      clientId: CLIENT_ID,
      token: token,
      question: question,
      deployment_id: deploymentId,
    });
  }
 
  // ==================== Invitations API ====================
 
  // Send invitation to share access to a beneficiary
  async sendInvitation(params: {
    beneficiaryId: string;
    email: string;
    role: 'caretaker' | 'guardian';
    label?: string;
  }): Promise<ApiResponse<{ invitation: { id: string; status: string } }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/invitations`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({
          beneficiaryId: params.beneficiaryId,
          email: params.email,
          role: params.role, // Backend expects 'caretaker' or 'guardian'
          label: params.label,
        }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to send invitation' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Get invitations for a beneficiary
  async getInvitations(beneficiaryId: string): Promise<ApiResponse<{
    invitations: {
      id: string;
      email: string;
      role: string;
      label?: string;
      status: string;
      created_at: string;
    }[]
  }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/invitations/beneficiary/${beneficiaryId}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to get invitations' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Delete invitation
  async deleteInvitation(invitationId: string): Promise<ApiResponse<{ success: boolean }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/invitations/${invitationId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to delete invitation' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Accept invitation code
  async acceptInvitation(code: string): Promise<ApiResponse<{
    success: boolean;
    message: string;
    beneficiary?: {
      id: number;
      firstName: string | null;
      lastName: string | null;
      email: string | null;
    };
    role?: string;
  }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/invitations/accept`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ code }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to accept invitation' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Activate equipment for beneficiary (saves to server)
  async activateBeneficiary(beneficiaryId: number, serialNumber: string): Promise<ApiResponse<{
    success: boolean;
    beneficiary: {
      id: number;
      firstName: string | null;
      lastName: string | null;
      hasDevices: boolean;
      equipmentStatus: string;
      device_id: string;
    };
  }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/me/beneficiaries/${beneficiaryId}/activate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ serialNumber }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to activate equipment' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // ==================== SUBSCRIPTION MANAGEMENT ====================
 
  // Cancel subscription at period end
  async cancelSubscription(beneficiaryId: number): Promise<ApiResponse<{ success: boolean; cancelAt: string }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/stripe/cancel-subscription`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ beneficiaryId }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to cancel subscription' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Get transaction history from Stripe
  async getTransactionHistory(beneficiaryId: number, limit = 10): Promise<ApiResponse<{
    transactions: {
      id: string;
      type: 'subscription' | 'one_time';
      amount: number;
      currency: string;
      status: string;
      date: string;
      description: string;
      invoicePdf?: string;
      hostedUrl?: string;
      receiptUrl?: string;
    }[];
    hasMore: boolean;
  }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/stripe/transaction-history/${beneficiaryId}?limit=${limit}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to get transaction history' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Reactivate subscription that was set to cancel
  async reactivateSubscription(beneficiaryId: number): Promise<ApiResponse<{ success: boolean; status: string }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/stripe/reactivate-subscription`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ beneficiaryId }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to reactivate subscription' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Update invitation role
  async updateInvitation(invitationId: string, role: 'caretaker' | 'guardian'): Promise<ApiResponse<{ success: boolean; invitation: { id: string; role: string; email: string } }>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/invitations/${invitationId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ role }),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to update invitation' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // ==================== NOTIFICATION SETTINGS ====================
 
  // Get notification settings for current user
  async getNotificationSettings(): Promise<ApiResponse<NotificationSettings>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/notification-settings`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data: data.settings, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to get notification settings' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Get notification history for current user
  async getNotificationHistory(options?: {
    limit?: number;
    offset?: number;
    type?: string;
    status?: string;
  }): Promise<ApiResponse<NotificationHistoryResponse>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      // Build query params
      const params = new URLSearchParams();
      if (options?.limit) params.append('limit', String(options.limit));
      if (options?.offset) params.append('offset', String(options.offset));
      if (options?.type) params.append('type', options.type);
      if (options?.status) params.append('status', options.status);
 
      const queryString = params.toString();
      const url = `${WELLNUO_API_URL}/notification-settings/history${queryString ? `?${queryString}` : ''}`;
 
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to get notification history' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // Update notification settings for current user
  async updateNotificationSettings(settings: Partial<NotificationSettings>): Promise<ApiResponse<NotificationSettings>> {
    const token = await this.getToken();
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${WELLNUO_API_URL}/notification-settings`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(settings),
      });
 
      const data = await response.json();
 
      if (response.ok) {
        return { data: data.settings, ok: true };
      }
 
      return {
        ok: false,
        error: { message: data.error || 'Failed to update notification settings' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Network error. Please check your connection.' },
      };
    }
  }
 
  // ==========================================
  // Legacy Dashboard Methods (Developer Mode)
  // For eluxnetworks.net dashboard WebView
  // ==========================================
 
  // Demo credentials for legacy dashboard
  private readonly DEMO_LEGACY_USER = 'robster';
  private readonly DEMO_LEGACY_PASSWORD = 'rob2';
  private readonly DEMO_DEPLOYMENT_ID = 21; // Ferdinand's deployment
 
  // Login to legacy dashboard API
  async loginToLegacyDashboard(): Promise<ApiResponse<AuthResponse>> {
    try {
      const formData = new URLSearchParams();
      formData.append('function', 'credentials');
      formData.append('user_name', this.DEMO_LEGACY_USER);
      formData.append('ps', this.DEMO_LEGACY_PASSWORD);
      formData.append('clientId', CLIENT_ID);
      formData.append('nonce', this.generateNonce());
 
      const response = await fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData.toString(),
      });
 
      const data = await response.json();
 
      // Check that access_token is a valid JWT string (not 0 or empty)
      if (data.status === '200 OK' && data.access_token && typeof data.access_token === 'string' && data.access_token.includes('.')) {
        // Save legacy credentials
        await SecureStore.setItemAsync('legacyAccessToken', data.access_token);
        await SecureStore.setItemAsync('legacyUserId', String(data.user_id));
        await SecureStore.setItemAsync('legacyUserName', this.DEMO_LEGACY_USER);
 
        return { data: data as AuthResponse, ok: true };
      }
      return {
        ok: false,
        error: { message: data.message || 'Legacy login failed - invalid credentials' },
      };
    } catch (error) {
      return {
        ok: false,
        error: { message: 'Failed to connect to dashboard API' },
      };
    }
  }
 
  // Refresh legacy token
  async refreshLegacyToken(): Promise<ApiResponse<AuthResponse>> {
    return this.loginToLegacyDashboard();
  }
 
  // Check if legacy token is expiring soon (within 1 hour)
  async isLegacyTokenExpiringSoon(): Promise<boolean> {
    try {
      const token = await this.getLegacyToken();
      if (!token) return true;
 
      // Decode JWT to get expiration
      const parts = token.split('.');
      if (parts.length !== 3) return true;
 
      const payload = JSON.parse(atob(parts[1]));
      const exp = payload.exp;
      if (!exp) return true;
 
      const now = Math.floor(Date.now() / 1000);
      const oneHour = 60 * 60;
 
      const isExpiring = (exp - now) < oneHour;
      return isExpiring;
    } catch (e) {
      return true;
    }
  }
 
  // Get legacy credentials for WebView injection
  async getLegacyWebViewCredentials(): Promise<{
    token: string;
    userName: string;
    userId: string;
  } | null> {
    try {
      const token = await SecureStore.getItemAsync('legacyAccessToken');
      const userName = await SecureStore.getItemAsync('legacyUserName');
      const userId = await SecureStore.getItemAsync('legacyUserId');
 
      // Check if credentials exist AND token is valid JWT (contains dots)
      const isValidToken = token && typeof token === 'string' && token.includes('.');
 
      // Additional check: verify token is not expired and userName matches expected
      let needsRefresh = false;
      if (isValidToken && userName && userId) {
        // Check if userName matches expected demo user
        if (userName !== this.DEMO_LEGACY_USER) {
          needsRefresh = true;
        }
 
        // Check if token is expired
        if (!needsRefresh) {
          try {
            const parts = token.split('.');
            if (parts.length === 3) {
              const payload = JSON.parse(atob(parts[1]));
              const exp = payload.exp;
              if (exp) {
                const now = Math.floor(Date.now() / 1000);
                if (now >= exp) {
                  needsRefresh = true;
                }
              }
            }
          } catch (e) {
            needsRefresh = true;
          }
        }
      }
 
      if (!isValidToken || !userName || !userId || needsRefresh) {
        // Clear any invalid/stale cached credentials
        await SecureStore.deleteItemAsync('legacyAccessToken');
        await SecureStore.deleteItemAsync('legacyUserName');
        await SecureStore.deleteItemAsync('legacyUserId');
 
        const loginResult = await this.loginToLegacyDashboard();
        if (!loginResult.ok) return null;
 
        // Get freshly saved credentials
        const newToken = await SecureStore.getItemAsync('legacyAccessToken');
        const newUserName = await SecureStore.getItemAsync('legacyUserName');
        const newUserId = await SecureStore.getItemAsync('legacyUserId');
 
        if (!newToken || !newUserName || !newUserId) return null;
        return { token: newToken, userName: newUserName, userId: newUserId };
      }
 
      return { token, userName, userId };
    } catch (e) {
      return null;
    }
  }
 
  // Get demo deployment ID
  getDemoDeploymentId(): number {
    return this.DEMO_DEPLOYMENT_ID;
  }
 
  /**
   * Get Legacy API credentials for device operations
   * Uses the same credentials as getLegacyWebViewCredentials but returns only what's needed
   */
  async getLegacyCredentials(): Promise<{ userName: string; token: string } | null> {
    const creds = await this.getLegacyWebViewCredentials();
    if (!creds) return null;
    return { userName: creds.userName, token: creds.token };
  }
 
  // ============================================================================
  // WP SENSORS / DEVICES MANAGEMENT
  // ============================================================================
 
  /**
   * Get all devices for a beneficiary
   * Returns WP sensors with online/offline status
   */
  async getDevicesForBeneficiary(beneficiaryId: string) {
    try {
 
      // Get auth token for WellNuo API
      const token = await this.getToken();
      if (!token) {
        return { ok: false, error: 'Not authenticated' };
      }
 
      // Get beneficiary's deployment_id from PostgreSQL
      const response = await fetch(`${this.baseUrl}/me/beneficiaries/${beneficiaryId}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
      if (!response.ok) {
        throw new Error('Failed to get beneficiary');
      }
 
      const beneficiary = await response.json();
      const deploymentId = beneficiary.deploymentId;
 
      if (!deploymentId) {
        return { ok: true, data: [] }; // No deployment = no devices
      }
 
      // Get Legacy API credentials
      const creds = await this.getLegacyCredentials();
      if (!creds) {
        return { ok: false, error: 'Not authenticated with Legacy API' };
      }
 
      // Get devices from Legacy API
      const formData = new URLSearchParams({
        function: 'device_list_by_deployment',
        user_name: creds.userName,
        token: creds.token,
        deployment_id: deploymentId.toString(),
        first: '0',
        last: '100',
      });
 
 
      const devicesResponse = await fetch(this.legacyApiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString(),
      });
 
      if (!devicesResponse.ok) {
        throw new Error('Failed to fetch devices from Legacy API');
      }
 
      const devicesData = await devicesResponse.json();
 
      if (!devicesData.result_list || devicesData.result_list.length === 0) {
        return { ok: true, data: [] };
      }
 
 
      // Get online status
      const onlineDevices = await this.getOnlineDevices(deploymentId);
 
      // Transform to WPSensor format with status calculation
      const sensors: WPSensor[] = devicesData.result_list.map((device: any) => {
        const [deviceId, wellId, mac, lastSeenTimestamp, location, description] = device;
        const lastSeen = new Date(lastSeenTimestamp * 1000);
 
        // Calculate status based on lastSeen time
        const now = new Date();
        const diffMinutes = (now.getTime() - lastSeen.getTime()) / (1000 * 60);
 
        let status: 'online' | 'warning' | 'offline';
        if (diffMinutes < 5) {
          status = 'online';   // 🟢 Fresh data
        } else if (diffMinutes < 60) {
          status = 'warning';  // 🟡 Might be issue
        } else {
          status = 'offline';  // 🔴 Definitely problem
        }
 
        // Convert location from Legacy API format to our ID
        // Legacy API may return:
        // - Numeric code: 104 or "104" -> convert to "kitchen"
        // - Label string: "Kitchen" -> convert to "kitchen"
        // - Our ID: "kitchen" -> keep as is
        let locationId = '';
        if (location) {
          const locationStr = String(location).trim();
          const numericLocation = parseInt(locationStr, 10);
 
          if (!isNaN(numericLocation) && String(numericLocation) === locationStr) {
            // It's a numeric code (e.g., 104 or "104")
            locationId = getLocationIdFromCode(numericLocation) || '';
          } else {
            // It's a string - try to match by label first, then by ID
            const byLabel = getLocationIdFromLabel(locationStr);
            if (byLabel) {
              locationId = byLabel;
            } else {
              // Check if it's already a valid ID
              const byId = ROOM_LOCATIONS.find(loc => loc.id === locationStr.toLowerCase());
              locationId = byId ? byId.id : locationStr;
            }
          }
        }
 
        return {
          deviceId: deviceId.toString(),
          wellId: parseInt(wellId, 10),
          mac: mac,
          name: `WP_${wellId}_${mac.slice(-6).toLowerCase()}`,
          status: status,
          lastSeen: lastSeen,
          location: locationId,
          description: description || '',
          beneficiaryId: beneficiaryId,
          deploymentId: deploymentId,
          source: 'api', // From API = attached to beneficiary
        };
      });
 
      return { ok: true, data: sensors };
    } catch (error: any) {
      return { ok: false, error: error.message };
    }
  }
 
  /**
   * Get online devices for a deployment (using fresh=true)
   * Returns Set of device_ids that are online
   */
  private async getOnlineDevices(deploymentId: number): Promise<Set<number>> {
    try {
      const creds = await this.getLegacyCredentials();
      if (!creds) return new Set();
 
      const formData = new URLSearchParams({
        function: 'request_devices',
        user_name: creds.userName,
        token: creds.token,
        deployment_id: deploymentId.toString(),
        group_id: 'All',
        location: 'All',
        fresh: 'true', // Only online devices
      });
 
      const response = await fetch(this.legacyApiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString(),
      });
 
      if (!response.ok) return new Set();
 
      const data = await response.json();
 
      if (!data.result_list) return new Set();
 
      // Extract device_ids from result
      const deviceIds = data.result_list.map((device: any) => device[0]);
      return new Set(deviceIds);
    } catch (error) {
      return new Set();
    }
  }
 
  /**
   * Get deployment_id for a beneficiary
   * @param beneficiaryId - The ID of the beneficiary
   * @returns ApiResponse with deployment_id or error
   */
  async getDeploymentForBeneficiary(beneficiaryId: string): Promise<ApiResponse<number>> {
    try {
      // Get auth token for WellNuo API
      const token = await this.getToken();
      if (!token) {
        return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
      }
 
      // Get beneficiary details from WellNuo API
      const response = await fetch(`${this.baseUrl}/me/beneficiaries/${beneficiaryId}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      if (!response.ok) {
        return {
          ok: false,
          error: {
            message: `Failed to get beneficiary: ${response.status}`,
            code: 'FETCH_ERROR'
          }
        };
      }
 
      const beneficiary = await response.json();
      const deploymentId = beneficiary.deploymentId;
 
      if (!deploymentId) {
        return {
          ok: false,
          error: {
            message: 'No deployment configured for this beneficiary. Please remove and re-add the beneficiary to fix this.',
            code: 'NO_DEPLOYMENT'
          }
        };
      }
 
      return { ok: true, data: deploymentId };
    } catch (error: any) {
      return {
        ok: false,
        error: {
          message: error.message || 'Failed to get deployment',
          code: 'EXCEPTION'
        }
      };
    }
  }
 
  /**
   * Attach device to beneficiary's deployment
   */
  async attachDeviceToBeneficiary(
    beneficiaryId: string,
    wellId: number,
    deviceMac: string
  ): Promise<ApiResponse<{ success: true }>> {
    try {
      // Get deployment ID for beneficiary
      const deploymentResponse = await this.getDeploymentForBeneficiary(beneficiaryId);
      if (!deploymentResponse.ok) {
        return {
          ok: false,
          error: {
            message: 'Could not find beneficiary deployment',
            code: 'DEPLOYMENT_NOT_FOUND',
            status: 404,
          }
        };
      }
 
      const deploymentId = deploymentResponse.data;
 
      const creds = await this.getLegacyCredentials();
      if (!creds) {
        return {
          ok: false,
          error: {
            message: 'Not authenticated. Please log in again.',
            code: 'UNAUTHORIZED',
            status: 401,
          }
        };
      }
 
      // Use device_form to attach device to deployment
      // Per Robert's documentation: requires well_id + device_mac + deployment_id
      const formData = new URLSearchParams({
        function: 'device_form',
        user_name: creds.userName,
        token: creds.token,
        well_id: wellId.toString(),
        device_mac: deviceMac.toUpperCase(),
        deployment_id: deploymentId.toString(),
      });
 
      const attachResponse = await fetch(this.legacyApiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString(),
      });
 
      if (!attachResponse.ok) {
        // Provide more specific error messages based on HTTP status
        let errorMessage = 'Could not register sensor. Please try again.';
        let errorCode = 'API_ERROR';
 
        if (attachResponse.status === 401 || attachResponse.status === 403) {
          errorMessage = 'Authentication expired. Please log in again.';
          errorCode = 'UNAUTHORIZED';
        } else if (attachResponse.status === 404) {
          errorMessage = 'Sensor or deployment not found.';
          errorCode = 'NOT_FOUND';
        } else if (attachResponse.status === 500) {
          errorMessage = 'Server error. Please try again later.';
          errorCode = 'SERVER_ERROR';
        } else if (attachResponse.status >= 500) {
          errorMessage = 'Service unavailable. Please check your internet connection.';
          errorCode = 'SERVICE_UNAVAILABLE';
        }
 
        return {
          ok: false,
          error: {
            message: errorMessage,
            code: errorCode,
            status: attachResponse.status,
          }
        };
      }
 
      const data = await attachResponse.json();
 
      if (data.status !== '200 OK') {
        // Parse Legacy API error response
        const errorMessage = data.message || 'Failed to register sensor';
 
        return {
          ok: false,
          error: {
            message: errorMessage,
            code: 'LEGACY_API_ERROR',
            status: attachResponse.status,
          }
        };
      }
 
      return { ok: true, data: { success: true } };
    } catch (error: any) {
      // Handle network errors and unexpected exceptions
      const isNetworkError = error.message?.includes('network') ||
                            error.message?.includes('fetch') ||
                            (typeof navigator !== 'undefined' && !navigator.onLine);
 
      return {
        ok: false,
        error: {
          message: isNetworkError
            ? 'No internet connection. Please check your network.'
            : 'An unexpected error occurred. Please try again.',
          code: isNetworkError ? 'NETWORK_ERROR' : 'EXCEPTION',
        }
      };
    }
  }
 
  /**
   * Update device metadata (location, description) in Legacy API
   * Uses device_form endpoint
   */
  async updateDeviceMetadata(
    deviceId: string,
    updates: {
      location?: string;  // Location ID (e.g., 'bedroom', 'kitchen') - will be converted to Legacy API code
      description?: string;
    }
  ): Promise<ApiResponse<{ success: boolean }>> {
    try {
      const creds = await this.getLegacyWebViewCredentials();
      if (!creds) {
        return { ok: false, error: { message: 'Not authenticated with Legacy API', code: 'UNAUTHORIZED' } };
      }
 
      const formData = new URLSearchParams({
        function: 'device_form',
        user_name: creds.userName,
        token: creds.token,
        device_id: deviceId,
      });
 
      // Add optional fields if provided
      // Location must be converted from ID to Legacy API numeric code
      if (updates.location !== undefined) {
        const legacyCode = getLocationLegacyCode(updates.location);
        if (legacyCode !== undefined) {
          formData.append('location', legacyCode.toString());
        } else {
          // If location ID not found, log warning but don't fail
        }
      }
      if (updates.description !== undefined) {
        formData.append('description', updates.description);
      }
 
      const response = await fetch(API_BASE_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString(),
      });
 
      if (!response.ok) {
        return { ok: false, error: { message: 'Failed to update device' } };
      }
 
      const data = await response.json();
 
      if (data.status !== '200 OK') {
        return { ok: false, error: { message: data.message || 'Failed to update device' } };
      }
 
      return { ok: true, data: { success: true } };
    } catch (error: any) {
      return { ok: false, error: { message: error.message || 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  /**
   * Attach device to deployment via Legacy API
   * Uses set_deployment endpoint to link a WP sensor to a beneficiary's deployment
   *
   * @param deploymentId - The deployment ID to attach the device to
   * @param wellId - The device's well_id (from BLE scan, e.g., 497)
   * @param ssid - WiFi network SSID
   * @param password - WiFi network password
   */
  async attachDeviceToDeployment(
    deploymentId: number,
    wellId: number,
    ssid: string,
    password: string
  ): Promise<ApiResponse<{ success: boolean }>> {
    try {
      const creds = await this.getLegacyWebViewCredentials();
      if (!creds) {
        return { ok: false, error: { message: 'Not authenticated with Legacy API', code: 'UNAUTHORIZED' } };
      }
 
      // Call set_deployment to attach device
      const formData = new URLSearchParams({
        function: 'set_deployment',
        user_name: creds.userName,
        token: creds.token,
        deployment: deploymentId.toString(),
        devices: JSON.stringify([wellId]),
        wifis: JSON.stringify([`${ssid}|${password}`]),
        reuse_existing_devices: '1',
      });
 
      const response = await fetch(API_BASE_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString(),
      });
 
      if (!response.ok) {
        return { ok: false, error: { message: 'Failed to attach device to deployment' } };
      }
 
      const data = await response.json();
 
      if (data.status !== '200 OK') {
        return { ok: false, error: { message: data.message || 'Failed to attach device' } };
      }
 
      return { ok: true, data: { success: true } };
    } catch (error: any) {
      return { ok: false, error: { message: error.message || 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  /**
   * Detach device from beneficiary
   */
  async detachDeviceFromBeneficiary(beneficiaryId: string, deviceId: string) {
    try {
      const creds = await this.getLegacyCredentials();
      if (!creds) throw new Error('Not authenticated with Legacy API');
 
      // Set device's deployment to 0 (unassigned)
      const formData = new URLSearchParams({
        function: 'device_form',
        user_name: creds.userName,
        token: creds.token,
        device_id: deviceId,
        deployment_id: '0', // Unassign
      });
 
      const response = await fetch(this.legacyApiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString(),
      });
 
      if (!response.ok) throw new Error('Failed to detach device');
 
      return { ok: true };
    } catch (error: any) {
      return { ok: false, error: error.message };
    }
  }
 
  /**
   * Get sensor health history from WellNuo API
   * Returns aggregated health metrics over time
   */
  async getSensorHealthHistory(
    deviceId: string,
    timeRange: '24h' | '7d' | '30d' = '24h'
  ): Promise<ApiResponse<{
    deviceId: string;
    timeRange: string;
    dataPoints: Array<{
      timestamp: number;
      connectionStatus: 'online' | 'warning' | 'offline';
      wifiRssi: number | null;
      communicationSuccessRate: number;
    }>;
    summary: {
      uptimePercentage: number;
      averageWifiRssi: number | null;
      totalCommands: number;
      successRate: number;
    };
  }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${this.baseUrl}/sensors/${deviceId}/health?range=${timeRange}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return {
          ok: false,
          error: {
            message: data.error || 'Failed to get sensor health history',
            code: response.status === 401 ? 'UNAUTHORIZED' : 'API_ERROR',
          }
        };
      }
 
      return { data, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
 
  /**
   * Report sensor health metrics to WellNuo API
   * Called periodically by the app to log sensor health data
   */
  async reportSensorHealth(metrics: {
    wellId: number;
    mac: string;
    connectionStatus: 'online' | 'warning' | 'offline';
    wifiRssi: number | null;
    wifiSsid: string | null;
    bleRssi: number | null;
    communicationStats: {
      successfulCommands: number;
      failedCommands: number;
      averageResponseTime: number;
    };
  }): Promise<ApiResponse<{ success: boolean }>> {
    const token = await this.getToken();
 
    if (!token) {
      return { ok: false, error: { message: 'Not authenticated', code: 'UNAUTHORIZED' } };
    }
 
    try {
      const response = await fetch(`${this.baseUrl}/sensors/health/report`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(metrics),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        return {
          ok: false,
          error: {
            message: data.error || 'Failed to report sensor health',
          }
        };
      }
 
      return { data: { success: true }, ok: true };
    } catch (error) {
      return { ok: false, error: { message: 'Network error', code: 'NETWORK_ERROR' } };
    }
  }
}
 
export const api = new ApiService();