grub-core 0.1.0

Core library for the grub calorie tracker — models, database, and service layer
Documentation
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
use std::collections::HashMap;
use std::path::Path;

use anyhow::{Context, Result};
use chrono::{Datelike, Local, NaiveDate};
use rusqlite::{Connection, params};
use uuid::Uuid;

use crate::models::{
    DailySummary, DailyTarget, ExportData, ExportMealEntry, ExportRecipe, ExportRecipeIngredient,
    ExportTarget, ExportWeightEntry, Food, ImportSummary, MEAL_TYPES, MealEntry, MealGroup,
    NewFood, NewMealEntry, NewWeightEntry, RecentFood, Recipe, RecipeDetail, RecipeIngredient,
    SyncPayload, SyncTombstone, UpdateMealEntry, WeightEntry,
};

pub struct Database {
    conn: Connection,
}

impl Database {
    pub fn open(path: &Path) -> Result<Self> {
        let conn = Connection::open(path)
            .with_context(|| format!("Failed to open database: {}", path.display()))?;
        let db = Database { conn };
        db.migrate()?;
        Ok(db)
    }

    pub fn open_in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        let db = Database { conn };
        db.migrate()?;
        Ok(db)
    }

    #[allow(clippy::too_many_lines)]
    fn migrate(&self) -> Result<()> {
        let version: i64 = self
            .conn
            .pragma_query_value(None, "user_version", |row| row.get(0))?;

        if version < 1 {
            self.conn.execute_batch(
                "CREATE TABLE IF NOT EXISTS foods (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    brand TEXT,
                    barcode TEXT UNIQUE,
                    calories_per_100g REAL NOT NULL,
                    protein_per_100g REAL,
                    carbs_per_100g REAL,
                    fat_per_100g REAL,
                    default_serving_g REAL,
                    source TEXT NOT NULL,
                    created_at TEXT NOT NULL
                );

                CREATE TABLE IF NOT EXISTS meal_entries (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    date TEXT NOT NULL,
                    meal_type TEXT NOT NULL,
                    food_id INTEGER NOT NULL REFERENCES foods(id),
                    serving_g REAL NOT NULL,
                    created_at TEXT NOT NULL
                );

                CREATE TABLE IF NOT EXISTS recipes (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    food_id INTEGER NOT NULL UNIQUE REFERENCES foods(id),
                    portions REAL NOT NULL DEFAULT 1.0,
                    created_at TEXT NOT NULL
                );

                CREATE TABLE IF NOT EXISTS recipe_ingredients (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    recipe_id INTEGER NOT NULL REFERENCES recipes(id) ON DELETE CASCADE,
                    food_id INTEGER NOT NULL REFERENCES foods(id),
                    quantity_g REAL NOT NULL
                );

                CREATE INDEX IF NOT EXISTS idx_meal_entries_date ON meal_entries(date);
                CREATE INDEX IF NOT EXISTS idx_foods_barcode ON foods(barcode);
                CREATE INDEX IF NOT EXISTS idx_foods_name ON foods(name);
                CREATE INDEX IF NOT EXISTS idx_recipe_ingredients_recipe ON recipe_ingredients(recipe_id);

                CREATE TABLE IF NOT EXISTS targets (
                    day_of_week INTEGER PRIMARY KEY CHECK (day_of_week BETWEEN 0 AND 6),
                    calories INTEGER NOT NULL,
                    protein_pct INTEGER,
                    carbs_pct INTEGER,
                    fat_pct INTEGER,
                    updated_at TEXT NOT NULL
                );

                PRAGMA user_version = 1;",
            )?;
        }

        if version < 2 {
            // Add uuid and updated_at columns to existing tables
            self.conn.execute_batch(
                "ALTER TABLE foods ADD COLUMN uuid TEXT;
                 ALTER TABLE foods ADD COLUMN updated_at TEXT;
                 ALTER TABLE meal_entries ADD COLUMN uuid TEXT;
                 ALTER TABLE meal_entries ADD COLUMN updated_at TEXT;
                 ALTER TABLE recipes ADD COLUMN uuid TEXT;
                 ALTER TABLE recipes ADD COLUMN updated_at TEXT;
                 ALTER TABLE recipe_ingredients ADD COLUMN uuid TEXT;
                 ALTER TABLE recipe_ingredients ADD COLUMN updated_at TEXT;",
            )?;

            // Generate UUIDs for existing rows
            let now = Local::now().to_rfc3339();
            for table in &["foods", "meal_entries", "recipes"] {
                let ids: Vec<i64> = {
                    let mut stmt = self.conn.prepare(&format!("SELECT id FROM {table}"))?;
                    stmt.query_map([], |row| row.get(0))?
                        .collect::<Result<Vec<_>, _>>()?
                };
                for id in ids {
                    let uuid = Uuid::new_v4().to_string();
                    // Use created_at as updated_at for existing rows
                    let created_at: Option<String> = self
                        .conn
                        .query_row(
                            &format!("SELECT created_at FROM {table} WHERE id = ?1"),
                            params![id],
                            |row| row.get(0),
                        )
                        .ok();
                    let updated_at = created_at.unwrap_or_else(|| now.clone());
                    self.conn.execute(
                        &format!("UPDATE {table} SET uuid = ?1, updated_at = ?2 WHERE id = ?3"),
                        params![uuid, updated_at, id],
                    )?;
                }
            }
            // recipe_ingredients don't have created_at, use now()
            {
                let ids: Vec<i64> = {
                    let mut stmt = self.conn.prepare("SELECT id FROM recipe_ingredients")?;
                    stmt.query_map([], |row| row.get(0))?
                        .collect::<Result<Vec<_>, _>>()?
                };
                for id in ids {
                    let uuid = Uuid::new_v4().to_string();
                    self.conn.execute(
                        "UPDATE recipe_ingredients SET uuid = ?1, updated_at = ?2 WHERE id = ?3",
                        params![uuid, now, id],
                    )?;
                }
            }

            // Create unique indexes and new tables
            self.conn.execute_batch(
                "CREATE UNIQUE INDEX idx_foods_uuid ON foods(uuid);
                 CREATE UNIQUE INDEX idx_meal_entries_uuid ON meal_entries(uuid);
                 CREATE UNIQUE INDEX idx_recipes_uuid ON recipes(uuid);
                 CREATE UNIQUE INDEX idx_recipe_ingredients_uuid ON recipe_ingredients(uuid);

                 CREATE TABLE sync_tombstones (
                     uuid TEXT NOT NULL,
                     table_name TEXT NOT NULL,
                     deleted_at TEXT NOT NULL
                 );
                 CREATE INDEX idx_tombstones_uuid ON sync_tombstones(uuid);

                 CREATE TABLE config (
                     key TEXT PRIMARY KEY,
                     value TEXT NOT NULL
                 );

                 PRAGMA user_version = 2;",
            )?;
        }

        if version < 3 {
            self.conn.execute_batch(
                "ALTER TABLE meal_entries ADD COLUMN display_unit TEXT;
                 ALTER TABLE meal_entries ADD COLUMN display_quantity REAL;
                 PRAGMA user_version = 3;",
            )?;
        }

        if version < 4 {
            // Migrate targets table from single-row (id=1) to per-day-of-week schema.
            // Check if old schema has 'id' column (old single-row layout).
            let has_old_schema: bool = self.conn.prepare("SELECT id FROM targets LIMIT 0").is_ok();

            if has_old_schema {
                // Preserve existing target by applying it to all 7 days.
                self.conn.execute_batch(
                    "CREATE TABLE targets_new (
                        day_of_week INTEGER PRIMARY KEY CHECK (day_of_week BETWEEN 0 AND 6),
                        calories INTEGER NOT NULL,
                        protein_pct INTEGER,
                        carbs_pct INTEGER,
                        fat_pct INTEGER,
                        updated_at TEXT NOT NULL
                     );

                     INSERT OR IGNORE INTO targets_new (day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at)
                     SELECT d.day, t.calories, t.protein_pct, t.carbs_pct, t.fat_pct, t.updated_at
                     FROM targets t, (SELECT 0 AS day UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6) d
                     WHERE t.id = 1;

                     DROP TABLE targets;
                     ALTER TABLE targets_new RENAME TO targets;",
                )?;
            }

            self.conn.execute_batch("PRAGMA user_version = 4;")?;
        }

        if version < 5 {
            self.conn.execute_batch(
                "CREATE TABLE IF NOT EXISTS weight_entries (
                    id INTEGER PRIMARY KEY,
                    uuid TEXT NOT NULL DEFAULT (lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || substr(hex(randomblob(2)),2) || '-' || substr('89ab', abs(random()) % 4 + 1, 1) || substr(hex(randomblob(2)),2) || '-' || hex(randomblob(6)))),
                    date TEXT NOT NULL UNIQUE,
                    weight_kg REAL NOT NULL,
                    source TEXT NOT NULL DEFAULT 'manual',
                    notes TEXT,
                    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
                    updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
                );

                PRAGMA user_version = 5;",
            )?;
        }

        if version < 6 {
            self.conn.execute_batch(
                "CREATE TABLE IF NOT EXISTS user_settings (
                    key TEXT PRIMARY KEY NOT NULL,
                    value TEXT NOT NULL,
                    updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
                );

                PRAGMA user_version = 6;",
            )?;
        }

        Ok(())
    }

    // --- Row mapping helpers ---

    fn food_from_row(row: &rusqlite::Row) -> rusqlite::Result<Food> {
        Ok(Food {
            id: row.get(0)?,
            name: row.get(1)?,
            brand: row.get(2)?,
            barcode: row.get(3)?,
            calories_per_100g: row.get(4)?,
            protein_per_100g: row.get(5)?,
            carbs_per_100g: row.get(6)?,
            fat_per_100g: row.get(7)?,
            default_serving_g: row.get(8)?,
            source: row.get(9)?,
            created_at: row.get(10)?,
            uuid: row.get::<_, Option<String>>(11)?.unwrap_or_default(),
            updated_at: row.get::<_, Option<String>>(12)?.unwrap_or_default(),
        })
    }

    // Expects columns:
    // 0: me.id, 1: me.uuid, 2: me.date, 3: me.meal_type, 4: me.food_id,
    // 5: me.serving_g, 6: me.display_unit, 7: me.display_quantity,
    // 8: me.created_at, 9: me.updated_at,
    // 10: f.name, 11: f.brand, 12: f.calories_per_100g, 13: f.protein_per_100g,
    // 14: f.carbs_per_100g, 15: f.fat_per_100g
    fn meal_entry_from_row(row: &rusqlite::Row) -> rusqlite::Result<MealEntry> {
        let serving_g: f64 = row.get(5)?;
        let cal_100: f64 = row.get(12)?;
        let pro_100: Option<f64> = row.get(13)?;
        let carb_100: Option<f64> = row.get(14)?;
        let fat_100: Option<f64> = row.get(15)?;
        Ok(MealEntry {
            id: row.get(0)?,
            uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
            date: row.get(2)?,
            meal_type: row.get(3)?,
            food_id: row.get(4)?,
            serving_g,
            display_unit: row.get(6)?,
            display_quantity: row.get(7)?,
            created_at: row.get(8)?,
            updated_at: row.get::<_, Option<String>>(9)?.unwrap_or_default(),
            food_name: Some(row.get(10)?),
            food_brand: row.get(11)?,
            calories: Some(cal_100 * serving_g / 100.0),
            protein: pro_100.map(|v| v * serving_g / 100.0),
            carbs: carb_100.map(|v| v * serving_g / 100.0),
            fat: fat_100.map(|v| v * serving_g / 100.0),
        })
    }

    // --- Foods ---

    pub fn insert_food(&self, food: &NewFood) -> Result<Food> {
        let now = Local::now().to_rfc3339();
        let uuid = Uuid::new_v4().to_string();
        self.conn.execute(
            "INSERT INTO foods (name, brand, barcode, calories_per_100g, protein_per_100g, carbs_per_100g, fat_per_100g, default_serving_g, source, created_at, uuid, updated_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
            params![
                food.name,
                food.brand,
                food.barcode,
                food.calories_per_100g,
                food.protein_per_100g,
                food.carbs_per_100g,
                food.fat_per_100g,
                food.default_serving_g,
                food.source,
                now,
                uuid,
                now,
            ],
        )?;
        let id = self.conn.last_insert_rowid();
        self.get_food_by_id(id)
    }

    pub fn upsert_food_by_barcode(&self, food: &NewFood) -> Result<Food> {
        if let Some(barcode) = &food.barcode {
            if let Some(existing) = self.get_food_by_barcode(barcode)? {
                return Ok(existing);
            }
        }
        self.insert_food(food)
    }

    pub fn get_food_by_id(&self, id: i64) -> Result<Food> {
        self.conn
            .query_row(
                "SELECT * FROM foods WHERE id = ?1",
                params![id],
                Self::food_from_row,
            )
            .context("Food not found")
    }

    pub fn get_food_by_barcode(&self, barcode: &str) -> Result<Option<Food>> {
        let mut stmt = self
            .conn
            .prepare("SELECT * FROM foods WHERE barcode = ?1")?;
        let mut rows = stmt.query(params![barcode])?;
        if let Some(row) = rows.next()? {
            Ok(Some(Self::food_from_row(row)?))
        } else {
            Ok(None)
        }
    }

    pub fn search_foods_local(&self, query: &str) -> Result<Vec<Food>> {
        let escaped = query
            .replace('\\', "\\\\")
            .replace('%', "\\%")
            .replace('_', "\\_");
        let pattern = format!("%{escaped}%");
        let mut stmt = self.conn.prepare(
            "SELECT * FROM foods WHERE name LIKE ?1 ESCAPE '\\' OR brand LIKE ?1 ESCAPE '\\' ORDER BY name LIMIT 20",
        )?;
        let foods = stmt
            .query_map(params![pattern], Self::food_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(foods)
    }

    pub fn list_foods(&self, search: Option<&str>) -> Result<Vec<Food>> {
        if let Some(query) = search {
            return self.search_foods_local(query);
        }
        let mut stmt = self
            .conn
            .prepare("SELECT * FROM foods ORDER BY name LIMIT 100")?;
        let foods = stmt
            .query_map([], Self::food_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(foods)
    }

    // --- Meal Entries ---

    pub fn insert_meal_entry(&self, entry: &NewMealEntry) -> Result<MealEntry> {
        let now = Local::now().to_rfc3339();
        let uuid = Uuid::new_v4().to_string();
        let date_str = entry.date.format("%Y-%m-%d").to_string();
        self.conn.execute(
            "INSERT INTO meal_entries (date, meal_type, food_id, serving_g, display_unit, display_quantity, created_at, uuid, updated_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
            params![
                date_str,
                entry.meal_type,
                entry.food_id,
                entry.serving_g,
                entry.display_unit,
                entry.display_quantity,
                now,
                uuid,
                now,
            ],
        )?;
        let id = self.conn.last_insert_rowid();
        self.get_meal_entry(id)
    }

    pub fn get_meal_entry(&self, id: i64) -> Result<MealEntry> {
        self.conn
            .query_row(
                "SELECT me.id, me.uuid, me.date, me.meal_type, me.food_id, me.serving_g,
                        me.display_unit, me.display_quantity, me.created_at, me.updated_at,
                        f.name, f.brand, f.calories_per_100g, f.protein_per_100g, f.carbs_per_100g, f.fat_per_100g
                 FROM meal_entries me
                 JOIN foods f ON me.food_id = f.id
                 WHERE me.id = ?1",
                params![id],
                Self::meal_entry_from_row,
            )
            .context("Meal entry not found")
    }

    pub fn delete_meal_entry(&self, id: i64) -> Result<bool> {
        let rows = self
            .conn
            .execute("DELETE FROM meal_entries WHERE id = ?1", params![id])?;
        Ok(rows > 0)
    }

    pub fn update_meal_entry(&self, id: i64, update: &UpdateMealEntry) -> Result<MealEntry> {
        // Verify existence
        self.get_meal_entry(id)?;

        let now = Local::now().to_rfc3339();
        if let Some(serving_g) = update.serving_g {
            self.conn.execute(
                "UPDATE meal_entries SET serving_g = ?1, updated_at = ?2 WHERE id = ?3",
                params![serving_g, now, id],
            )?;
        }
        if let Some(ref meal_type) = update.meal_type {
            self.conn.execute(
                "UPDATE meal_entries SET meal_type = ?1, updated_at = ?2 WHERE id = ?3",
                params![meal_type, now, id],
            )?;
        }
        if let Some(date) = update.date {
            let date_str = date.format("%Y-%m-%d").to_string();
            self.conn.execute(
                "UPDATE meal_entries SET date = ?1, updated_at = ?2 WHERE id = ?3",
                params![date_str, now, id],
            )?;
        }
        if let Some(ref display_unit) = update.display_unit {
            self.conn.execute(
                "UPDATE meal_entries SET display_unit = ?1, updated_at = ?2 WHERE id = ?3",
                params![display_unit, now, id],
            )?;
        }
        if let Some(ref display_quantity) = update.display_quantity {
            self.conn.execute(
                "UPDATE meal_entries SET display_quantity = ?1, updated_at = ?2 WHERE id = ?3",
                params![display_quantity, now, id],
            )?;
        }

        self.get_meal_entry(id)
    }

    pub fn get_entries_for_date(&self, date: NaiveDate) -> Result<Vec<MealEntry>> {
        let date_str = date.format("%Y-%m-%d").to_string();
        let mut stmt = self.conn.prepare(
            "SELECT me.id, me.uuid, me.date, me.meal_type, me.food_id, me.serving_g,
                    me.display_unit, me.display_quantity, me.created_at, me.updated_at,
                    f.name, f.brand, f.calories_per_100g, f.protein_per_100g, f.carbs_per_100g, f.fat_per_100g
             FROM meal_entries me
             JOIN foods f ON me.food_id = f.id
             WHERE me.date = ?1
             ORDER BY me.id",
        )?;
        let entries = stmt
            .query_map(params![date_str], Self::meal_entry_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(entries)
    }

    pub fn get_entries_for_date_and_meal(
        &self,
        date: NaiveDate,
        meal_type: &str,
    ) -> Result<Vec<MealEntry>> {
        let date_str = date.format("%Y-%m-%d").to_string();
        let mut stmt = self.conn.prepare(
            "SELECT me.id, me.uuid, me.date, me.meal_type, me.food_id, me.serving_g,
                    me.display_unit, me.display_quantity, me.created_at, me.updated_at,
                    f.name, f.brand, f.calories_per_100g, f.protein_per_100g, f.carbs_per_100g, f.fat_per_100g
             FROM meal_entries me
             JOIN foods f ON me.food_id = f.id
             WHERE me.date = ?1 AND me.meal_type = ?2
             ORDER BY me.id",
        )?;
        let entries = stmt
            .query_map(params![date_str, meal_type], Self::meal_entry_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(entries)
    }

    // --- Targets ---

    pub fn set_target(
        &self,
        day_of_week: i64,
        calories: i64,
        protein_pct: Option<i64>,
        carbs_pct: Option<i64>,
        fat_pct: Option<i64>,
    ) -> Result<DailyTarget> {
        let now = Local::now().to_rfc3339();
        self.conn.execute(
            "INSERT OR REPLACE INTO targets (day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![day_of_week, calories, protein_pct, carbs_pct, fat_pct, now],
        )?;
        Ok(DailyTarget::from_db(
            day_of_week,
            calories,
            protein_pct,
            carbs_pct,
            fat_pct,
        ))
    }

    pub fn get_target(&self, day_of_week: i64) -> Result<Option<DailyTarget>> {
        let mut stmt = self.conn.prepare(
            "SELECT day_of_week, calories, protein_pct, carbs_pct, fat_pct FROM targets WHERE day_of_week = ?1",
        )?;
        let mut rows = stmt.query(params![day_of_week])?;
        if let Some(row) = rows.next()? {
            let day: i64 = row.get(0)?;
            let calories: i64 = row.get(1)?;
            let protein_pct: Option<i64> = row.get(2)?;
            let carbs_pct: Option<i64> = row.get(3)?;
            let fat_pct: Option<i64> = row.get(4)?;
            Ok(Some(DailyTarget::from_db(
                day,
                calories,
                protein_pct,
                carbs_pct,
                fat_pct,
            )))
        } else {
            Ok(None)
        }
    }

    pub fn get_all_targets(&self) -> Result<Vec<DailyTarget>> {
        let mut stmt = self.conn.prepare(
            "SELECT day_of_week, calories, protein_pct, carbs_pct, fat_pct FROM targets ORDER BY day_of_week",
        )?;
        let targets = stmt
            .query_map([], |row| {
                let day: i64 = row.get(0)?;
                let calories: i64 = row.get(1)?;
                let protein_pct: Option<i64> = row.get(2)?;
                let carbs_pct: Option<i64> = row.get(3)?;
                let fat_pct: Option<i64> = row.get(4)?;
                Ok(DailyTarget::from_db(
                    day,
                    calories,
                    protein_pct,
                    carbs_pct,
                    fat_pct,
                ))
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(targets)
    }

    pub fn clear_target(&self, day_of_week: i64) -> Result<bool> {
        let rows = self.conn.execute(
            "DELETE FROM targets WHERE day_of_week = ?1",
            params![day_of_week],
        )?;
        Ok(rows > 0)
    }

    pub fn clear_all_targets(&self) -> Result<bool> {
        let rows = self.conn.execute("DELETE FROM targets", [])?;
        Ok(rows > 0)
    }

    // --- Recipes ---

    pub fn create_recipe(&self, name: &str, portions: f64) -> Result<Recipe> {
        let now = Local::now().to_rfc3339();
        let uuid = Uuid::new_v4().to_string();
        // Create a placeholder virtual food with zero macros — will be recomputed on add-ingredient
        let food = self.insert_food(&NewFood {
            name: name.to_string(),
            brand: None,
            barcode: None,
            calories_per_100g: 0.0,
            protein_per_100g: Some(0.0),
            carbs_per_100g: Some(0.0),
            fat_per_100g: Some(0.0),
            default_serving_g: Some(0.0),
            source: "recipe".to_string(),
        })?;

        self.conn.execute(
            "INSERT INTO recipes (food_id, portions, created_at, uuid, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)",
            params![food.id, portions, now, uuid, now],
        )?;
        let id = self.conn.last_insert_rowid();
        Ok(Recipe {
            id,
            uuid,
            food_id: food.id,
            portions,
            created_at: now.clone(),
            updated_at: now,
        })
    }

    pub fn get_recipe_by_id(&self, id: i64) -> Result<Recipe> {
        self.conn
            .query_row(
                "SELECT id, uuid, food_id, portions, created_at, updated_at FROM recipes WHERE id = ?1",
                params![id],
                |row| {
                    Ok(Recipe {
                        id: row.get(0)?,
                        uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
                        food_id: row.get(2)?,
                        portions: row.get(3)?,
                        created_at: row.get(4)?,
                        updated_at: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
                    })
                },
            )
            .context("Recipe not found")
    }

    pub fn get_recipe_by_food_name(&self, name: &str) -> Result<Recipe> {
        self.conn
            .query_row(
                "SELECT r.id, r.uuid, r.food_id, r.portions, r.created_at, r.updated_at
                 FROM recipes r JOIN foods f ON r.food_id = f.id
                 WHERE LOWER(f.name) = LOWER(?1)",
                params![name],
                |row| {
                    Ok(Recipe {
                        id: row.get(0)?,
                        uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
                        food_id: row.get(2)?,
                        portions: row.get(3)?,
                        created_at: row.get(4)?,
                        updated_at: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
                    })
                },
            )
            .context(format!("Recipe '{name}' not found"))
    }

    pub fn add_recipe_ingredient(
        &self,
        recipe_id: i64,
        food_id: i64,
        quantity_g: f64,
    ) -> Result<RecipeIngredient> {
        let now = Local::now().to_rfc3339();
        let uuid = Uuid::new_v4().to_string();
        self.conn.execute(
            "INSERT INTO recipe_ingredients (recipe_id, food_id, quantity_g, uuid, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)",
            params![recipe_id, food_id, quantity_g, uuid, now],
        )?;
        let id = self.conn.last_insert_rowid();

        // Recompute virtual food
        self.recompute_recipe_food(recipe_id)?;

        Ok(RecipeIngredient {
            id,
            uuid,
            recipe_id,
            food_id,
            quantity_g,
            food_name: None,
            food_brand: None,
            calories: None,
            protein: None,
            carbs: None,
            fat: None,
        })
    }

    pub fn remove_recipe_ingredient(&self, recipe_id: i64, food_name: &str) -> Result<bool> {
        let rows = self.conn.execute(
            "DELETE FROM recipe_ingredients WHERE recipe_id = ?1 AND food_id IN (
                SELECT id FROM foods WHERE LOWER(name) = LOWER(?2)
            )",
            params![recipe_id, food_name],
        )?;
        if rows > 0 {
            self.recompute_recipe_food(recipe_id)?;
        }
        Ok(rows > 0)
    }

    pub fn set_recipe_portions(&self, recipe_id: i64, portions: f64) -> Result<()> {
        let now = Local::now().to_rfc3339();
        self.conn.execute(
            "UPDATE recipes SET portions = ?1, updated_at = ?2 WHERE id = ?3",
            params![portions, now, recipe_id],
        )?;
        self.recompute_recipe_food(recipe_id)?;
        Ok(())
    }

    pub fn get_recipe_ingredients(&self, recipe_id: i64) -> Result<Vec<RecipeIngredient>> {
        let mut stmt = self.conn.prepare(
            "SELECT ri.id, ri.uuid, ri.recipe_id, ri.food_id, ri.quantity_g,
                    f.name, f.brand, f.calories_per_100g, f.protein_per_100g, f.carbs_per_100g, f.fat_per_100g
             FROM recipe_ingredients ri
             JOIN foods f ON ri.food_id = f.id
             WHERE ri.recipe_id = ?1
             ORDER BY ri.id",
        )?;
        let ingredients = stmt
            .query_map(params![recipe_id], |row| {
                let qty: f64 = row.get(4)?;
                let cal_100: f64 = row.get(7)?;
                let pro_100: Option<f64> = row.get(8)?;
                let carb_100: Option<f64> = row.get(9)?;
                let fat_100: Option<f64> = row.get(10)?;
                Ok(RecipeIngredient {
                    id: row.get(0)?,
                    uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
                    recipe_id: row.get(2)?,
                    food_id: row.get(3)?,
                    quantity_g: qty,
                    food_name: Some(row.get(5)?),
                    food_brand: row.get(6)?,
                    calories: Some(cal_100 * qty / 100.0),
                    protein: pro_100.map(|v| v * qty / 100.0),
                    carbs: carb_100.map(|v| v * qty / 100.0),
                    fat: fat_100.map(|v| v * qty / 100.0),
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(ingredients)
    }

    pub fn get_recipe_detail(&self, recipe_id: i64) -> Result<RecipeDetail> {
        let recipe = self.get_recipe_by_id(recipe_id)?;
        let food = self.get_food_by_id(recipe.food_id)?;
        let ingredients = self.get_recipe_ingredients(recipe_id)?;

        let total_weight: f64 = ingredients.iter().map(|i| i.quantity_g).sum();
        let total_cal: f64 = ingredients.iter().filter_map(|i| i.calories).sum();
        let total_pro: f64 = ingredients.iter().filter_map(|i| i.protein).sum();
        let total_carbs: f64 = ingredients.iter().filter_map(|i| i.carbs).sum();
        let total_fat: f64 = ingredients.iter().filter_map(|i| i.fat).sum();

        Ok(RecipeDetail {
            id: recipe.id,
            uuid: recipe.uuid,
            food_id: recipe.food_id,
            name: food.name,
            portions: recipe.portions,
            total_weight_g: total_weight,
            per_portion_g: if recipe.portions > 0.0 {
                total_weight / recipe.portions
            } else {
                0.0
            },
            ingredients,
            per_portion_calories: if recipe.portions > 0.0 {
                total_cal / recipe.portions
            } else {
                0.0
            },
            per_portion_protein: if recipe.portions > 0.0 {
                total_pro / recipe.portions
            } else {
                0.0
            },
            per_portion_carbs: if recipe.portions > 0.0 {
                total_carbs / recipe.portions
            } else {
                0.0
            },
            per_portion_fat: if recipe.portions > 0.0 {
                total_fat / recipe.portions
            } else {
                0.0
            },
            calories_per_100g: food.calories_per_100g,
            protein_per_100g: food.protein_per_100g.unwrap_or(0.0),
            carbs_per_100g: food.carbs_per_100g.unwrap_or(0.0),
            fat_per_100g: food.fat_per_100g.unwrap_or(0.0),
        })
    }

    pub fn list_recipes(&self) -> Result<Vec<RecipeDetail>> {
        let mut stmt = self.conn.prepare("SELECT id FROM recipes ORDER BY id")?;
        let ids: Vec<i64> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;
        let mut details = Vec::new();
        for id in ids {
            details.push(self.get_recipe_detail(id)?);
        }
        Ok(details)
    }

    pub fn delete_recipe(&self, recipe_id: i64) -> Result<()> {
        let recipe = self.get_recipe_by_id(recipe_id)?;
        // Delete ingredients first (CASCADE should handle this, but be explicit)
        self.conn.execute(
            "DELETE FROM recipe_ingredients WHERE recipe_id = ?1",
            params![recipe_id],
        )?;
        self.conn
            .execute("DELETE FROM recipes WHERE id = ?1", params![recipe_id])?;
        // Delete the virtual food
        self.conn
            .execute("DELETE FROM foods WHERE id = ?1", params![recipe.food_id])?;
        Ok(())
    }

    fn recompute_recipe_food(&self, recipe_id: i64) -> Result<()> {
        let recipe = self.get_recipe_by_id(recipe_id)?;
        let ingredients = self.get_recipe_ingredients(recipe_id)?;

        let total_weight: f64 = ingredients.iter().map(|i| i.quantity_g).sum();
        let total_cal: f64 = ingredients.iter().filter_map(|i| i.calories).sum();
        let total_pro: f64 = ingredients.iter().filter_map(|i| i.protein).sum();
        let total_carbs: f64 = ingredients.iter().filter_map(|i| i.carbs).sum();
        let total_fat: f64 = ingredients.iter().filter_map(|i| i.fat).sum();

        let (cal_100, pro_100, carb_100, fat_100, serving_g) = if total_weight > 0.0 {
            (
                total_cal * 100.0 / total_weight,
                total_pro * 100.0 / total_weight,
                total_carbs * 100.0 / total_weight,
                total_fat * 100.0 / total_weight,
                total_weight / recipe.portions,
            )
        } else {
            (0.0, 0.0, 0.0, 0.0, 0.0)
        };

        let now = Local::now().to_rfc3339();
        self.conn.execute(
            "UPDATE foods SET calories_per_100g = ?1, protein_per_100g = ?2, carbs_per_100g = ?3,
             fat_per_100g = ?4, default_serving_g = ?5, updated_at = ?6 WHERE id = ?7",
            params![
                cal_100,
                pro_100,
                carb_100,
                fat_100,
                serving_g,
                now,
                recipe.food_id
            ],
        )?;
        Ok(())
    }

    // --- Sync support ---

    pub fn record_tombstone(&self, uuid: &str, table_name: &str) -> Result<()> {
        let now = Local::now().to_rfc3339();
        self.conn.execute(
            "INSERT INTO sync_tombstones (uuid, table_name, deleted_at) VALUES (?1, ?2, ?3)",
            params![uuid, table_name, now],
        )?;
        Ok(())
    }

    pub fn get_tombstones(&self) -> Result<Vec<SyncTombstone>> {
        let mut stmt = self
            .conn
            .prepare("SELECT uuid, table_name, deleted_at FROM sync_tombstones")?;
        let tombstones = stmt
            .query_map([], |row| {
                Ok(SyncTombstone {
                    uuid: row.get(0)?,
                    table_name: row.get(1)?,
                    deleted_at: row.get(2)?,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(tombstones)
    }

    pub fn get_tombstones_since(&self, since: &str) -> Result<Vec<SyncTombstone>> {
        let mut stmt = self.conn.prepare(
            "SELECT uuid, table_name, deleted_at FROM sync_tombstones WHERE deleted_at > ?1",
        )?;
        let tombstones = stmt
            .query_map(params![since], |row| {
                Ok(SyncTombstone {
                    uuid: row.get(0)?,
                    table_name: row.get(1)?,
                    deleted_at: row.get(2)?,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(tombstones)
    }

    pub fn clear_tombstones(&self) -> Result<()> {
        self.conn.execute("DELETE FROM sync_tombstones", [])?;
        Ok(())
    }

    // --- Delta sync ---

    pub fn get_foods_since(&self, since: &str) -> Result<Vec<Food>> {
        let mut stmt = self
            .conn
            .prepare("SELECT * FROM foods WHERE updated_at > ?1 ORDER BY id")?;
        let foods = stmt
            .query_map(params![since], Self::food_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(foods)
    }

    pub fn get_all_foods(&self) -> Result<Vec<Food>> {
        let mut stmt = self.conn.prepare("SELECT * FROM foods ORDER BY id")?;
        let foods = stmt
            .query_map([], Self::food_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(foods)
    }

    pub fn get_meal_entries_since(&self, since: &str) -> Result<Vec<ExportMealEntry>> {
        let mut stmt = self.conn.prepare(
            "SELECT me.id, me.uuid, me.date, me.meal_type, me.food_id, me.serving_g,
                    me.display_unit, me.display_quantity, me.created_at,
                    me.updated_at, f.uuid as food_uuid
             FROM meal_entries me JOIN foods f ON me.food_id = f.id
             WHERE me.updated_at > ?1
             ORDER BY me.id",
        )?;
        let entries = stmt
            .query_map(params![since], Self::export_meal_entry_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(entries)
    }

    pub fn get_all_meal_entries_export(&self) -> Result<Vec<ExportMealEntry>> {
        let mut stmt = self.conn.prepare(
            "SELECT me.id, me.uuid, me.date, me.meal_type, me.food_id, me.serving_g,
                    me.display_unit, me.display_quantity, me.created_at,
                    me.updated_at, f.uuid as food_uuid
             FROM meal_entries me JOIN foods f ON me.food_id = f.id
             ORDER BY me.id",
        )?;
        let entries = stmt
            .query_map([], Self::export_meal_entry_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(entries)
    }

    fn export_meal_entry_from_row(row: &rusqlite::Row) -> rusqlite::Result<ExportMealEntry> {
        Ok(ExportMealEntry {
            id: row.get(0)?,
            uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
            date: row.get(2)?,
            meal_type: row.get(3)?,
            food_id: row.get(4)?,
            serving_g: row.get(5)?,
            display_unit: row.get(6)?,
            display_quantity: row.get(7)?,
            created_at: row.get(8)?,
            updated_at: row.get::<_, Option<String>>(9)?.unwrap_or_default(),
            food_uuid: row.get::<_, Option<String>>(10)?.unwrap_or_default(),
        })
    }

    fn export_recipe_from_row(row: &rusqlite::Row) -> rusqlite::Result<ExportRecipe> {
        Ok(ExportRecipe {
            id: row.get(0)?,
            uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
            food_id: row.get(2)?,
            portions: row.get(3)?,
            created_at: row.get(4)?,
            updated_at: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
            food_uuid: row.get::<_, Option<String>>(6)?.unwrap_or_default(),
        })
    }

    fn export_recipe_ingredient_from_row(
        row: &rusqlite::Row,
    ) -> rusqlite::Result<ExportRecipeIngredient> {
        Ok(ExportRecipeIngredient {
            id: row.get(0)?,
            uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
            recipe_id: row.get(2)?,
            food_id: row.get(3)?,
            quantity_g: row.get(4)?,
            recipe_uuid: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
            food_uuid: row.get::<_, Option<String>>(6)?.unwrap_or_default(),
        })
    }

    fn export_target_from_row(row: &rusqlite::Row) -> rusqlite::Result<ExportTarget> {
        Ok(ExportTarget {
            day_of_week: row.get(0)?,
            calories: row.get(1)?,
            protein_pct: row.get(2)?,
            carbs_pct: row.get(3)?,
            fat_pct: row.get(4)?,
            updated_at: row.get(5)?,
        })
    }

    fn export_weight_entry_from_row(row: &rusqlite::Row) -> rusqlite::Result<ExportWeightEntry> {
        Ok(ExportWeightEntry {
            uuid: row.get(0)?,
            date: row.get(1)?,
            weight_kg: row.get(2)?,
            source: row.get(3)?,
            notes: row.get(4)?,
            created_at: row.get(5)?,
            updated_at: row.get::<_, Option<String>>(6)?.unwrap_or_default(),
        })
    }

    pub fn get_recipes_since(&self, since: &str) -> Result<Vec<ExportRecipe>> {
        let mut stmt = self.conn.prepare(
            "SELECT r.id, r.uuid, r.food_id, r.portions, r.created_at, r.updated_at, f.uuid as food_uuid
             FROM recipes r JOIN foods f ON r.food_id = f.id
             WHERE r.updated_at > ?1
             ORDER BY r.id",
        )?;
        let recipes = stmt
            .query_map(params![since], Self::export_recipe_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(recipes)
    }

    pub fn get_all_recipes_export(&self) -> Result<Vec<ExportRecipe>> {
        let mut stmt = self.conn.prepare(
            "SELECT r.id, r.uuid, r.food_id, r.portions, r.created_at, r.updated_at, f.uuid as food_uuid
             FROM recipes r JOIN foods f ON r.food_id = f.id
             ORDER BY r.id",
        )?;
        let recipes = stmt
            .query_map([], Self::export_recipe_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(recipes)
    }

    pub fn get_recipe_ingredients_since(&self, since: &str) -> Result<Vec<ExportRecipeIngredient>> {
        let mut stmt = self.conn.prepare(
            "SELECT ri.id, ri.uuid, ri.recipe_id, ri.food_id, ri.quantity_g,
                    r.uuid as recipe_uuid, f.uuid as food_uuid
             FROM recipe_ingredients ri
             JOIN recipes r ON ri.recipe_id = r.id
             JOIN foods f ON ri.food_id = f.id
             WHERE ri.updated_at > ?1
             ORDER BY ri.id",
        )?;
        let ingredients = stmt
            .query_map(params![since], Self::export_recipe_ingredient_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(ingredients)
    }

    pub fn get_all_recipe_ingredients_export(&self) -> Result<Vec<ExportRecipeIngredient>> {
        let mut stmt = self.conn.prepare(
            "SELECT ri.id, ri.uuid, ri.recipe_id, ri.food_id, ri.quantity_g,
                    r.uuid as recipe_uuid, f.uuid as food_uuid
             FROM recipe_ingredients ri
             JOIN recipes r ON ri.recipe_id = r.id
             JOIN foods f ON ri.food_id = f.id
             ORDER BY ri.id",
        )?;
        let ingredients = stmt
            .query_map([], Self::export_recipe_ingredient_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(ingredients)
    }

    pub fn get_targets_since(&self, since: &str) -> Result<Vec<ExportTarget>> {
        let mut stmt = self.conn.prepare(
            "SELECT day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at
             FROM targets WHERE updated_at > ?1
             ORDER BY day_of_week",
        )?;
        let targets = stmt
            .query_map(params![since], Self::export_target_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(targets)
    }

    pub fn get_all_targets_export(&self) -> Result<Vec<ExportTarget>> {
        let mut stmt = self.conn.prepare(
            "SELECT day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at
             FROM targets ORDER BY day_of_week",
        )?;
        let targets = stmt
            .query_map([], Self::export_target_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(targets)
    }

    pub fn get_weight_entries_since(&self, since: &str) -> Result<Vec<ExportWeightEntry>> {
        let mut stmt = self.conn.prepare(
            "SELECT uuid, date, weight_kg, source, notes, created_at, updated_at
             FROM weight_entries WHERE updated_at > ?1
             ORDER BY date",
        )?;
        let entries = stmt
            .query_map(params![since], Self::export_weight_entry_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(entries)
    }

    pub fn get_all_weight_entries_export(&self) -> Result<Vec<ExportWeightEntry>> {
        let mut stmt = self.conn.prepare(
            "SELECT uuid, date, weight_kg, source, notes, created_at, updated_at
             FROM weight_entries ORDER BY date",
        )?;
        let entries = stmt
            .query_map([], Self::export_weight_entry_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(entries)
    }

    pub fn changes_since(
        &self,
        since: Option<&str>,
        server_timestamp: &str,
    ) -> Result<SyncPayload> {
        let (foods, meal_entries, recipes, recipe_ingredients, targets, weight_entries, tombstones) =
            match since {
                Some(ts) => (
                    self.get_foods_since(ts)?,
                    self.get_meal_entries_since(ts)?,
                    self.get_recipes_since(ts)?,
                    self.get_recipe_ingredients_since(ts)?,
                    self.get_targets_since(ts)?,
                    self.get_weight_entries_since(ts)?,
                    self.get_tombstones_since(ts)?,
                ),
                None => (
                    self.get_all_foods()?,
                    self.get_all_meal_entries_export()?,
                    self.get_all_recipes_export()?,
                    self.get_all_recipe_ingredients_export()?,
                    self.get_all_targets_export()?,
                    self.get_all_weight_entries_export()?,
                    self.get_tombstones()?,
                ),
            };
        Ok(SyncPayload {
            foods,
            meal_entries,
            recipes,
            recipe_ingredients,
            targets,
            weight_entries,
            tombstones,
            server_timestamp: server_timestamp.to_string(),
        })
    }

    #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
    pub fn apply_remote_changes(
        &self,
        foods: &[Food],
        meal_entries: &[ExportMealEntry],
        recipes: &[ExportRecipe],
        recipe_ingredients: &[ExportRecipeIngredient],
        targets: &[ExportTarget],
        weight_entries: &[ExportWeightEntry],
        tombstones: &[SyncTombstone],
    ) -> Result<()> {
        // Step 1: Merge foods — build uuid→local_id mapping
        let mut food_uuid_to_local_id: HashMap<String, i64> = HashMap::new();
        for food in foods {
            if food.uuid.is_empty() {
                continue;
            }
            if let Some(existing) = self.get_food_by_uuid(&food.uuid)? {
                food_uuid_to_local_id.insert(food.uuid.clone(), existing.id);
                if food.updated_at > existing.updated_at {
                    self.conn.execute(
                        "UPDATE foods SET name=?1, brand=?2, barcode=?3, calories_per_100g=?4,
                         protein_per_100g=?5, carbs_per_100g=?6, fat_per_100g=?7,
                         default_serving_g=?8, source=?9, updated_at=?10 WHERE uuid=?11",
                        params![
                            food.name,
                            food.brand,
                            food.barcode,
                            food.calories_per_100g,
                            food.protein_per_100g,
                            food.carbs_per_100g,
                            food.fat_per_100g,
                            food.default_serving_g,
                            food.source,
                            food.updated_at,
                            food.uuid,
                        ],
                    )?;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO foods (name, brand, barcode, calories_per_100g,
                     protein_per_100g, carbs_per_100g, fat_per_100g,
                     default_serving_g, source, created_at, uuid, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                    params![
                        food.name,
                        food.brand,
                        food.barcode,
                        food.calories_per_100g,
                        food.protein_per_100g,
                        food.carbs_per_100g,
                        food.fat_per_100g,
                        food.default_serving_g,
                        food.source,
                        food.created_at,
                        food.uuid,
                        food.updated_at,
                    ],
                )?;
                let new_id = self.conn.last_insert_rowid();
                food_uuid_to_local_id.insert(food.uuid.clone(), new_id);
            }
        }

        // Step 2: Merge meal entries
        for entry in meal_entries {
            if entry.uuid.is_empty() {
                continue;
            }
            let local_food_id = if entry.food_uuid.is_empty() {
                None
            } else {
                food_uuid_to_local_id
                    .get(&entry.food_uuid)
                    .copied()
                    .or_else(|| {
                        self.get_food_by_uuid(&entry.food_uuid)
                            .ok()
                            .flatten()
                            .map(|f| f.id)
                    })
            };
            let Some(food_id) = local_food_id else {
                continue;
            };

            if let Some(existing_id) = self.get_meal_entry_by_uuid(&entry.uuid)? {
                let existing_updated: String = self.conn.query_row(
                    "SELECT COALESCE(updated_at, '') FROM meal_entries WHERE id = ?1",
                    params![existing_id],
                    |row| row.get(0),
                )?;
                if entry.updated_at > existing_updated {
                    self.conn.execute(
                        "UPDATE meal_entries SET date=?1, meal_type=?2, food_id=?3, serving_g=?4, display_unit=?5, display_quantity=?6, updated_at=?7 WHERE id=?8",
                        params![entry.date, entry.meal_type, food_id, entry.serving_g, entry.display_unit, entry.display_quantity, entry.updated_at, existing_id],
                    )?;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO meal_entries (date, meal_type, food_id, serving_g, display_unit, display_quantity, created_at, uuid, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
                    params![entry.date, entry.meal_type, food_id, entry.serving_g, entry.display_unit, entry.display_quantity, entry.created_at, entry.uuid, entry.updated_at],
                )?;
            }
        }

        // Step 3: Merge recipes — build recipe_uuid→local_id mapping
        let mut recipe_uuid_to_local_id: HashMap<String, i64> = HashMap::new();
        for recipe in recipes {
            if recipe.uuid.is_empty() {
                continue;
            }
            let local_food_id = if recipe.food_uuid.is_empty() {
                None
            } else {
                food_uuid_to_local_id
                    .get(&recipe.food_uuid)
                    .copied()
                    .or_else(|| {
                        self.get_food_by_uuid(&recipe.food_uuid)
                            .ok()
                            .flatten()
                            .map(|f| f.id)
                    })
            };
            let Some(food_id) = local_food_id else {
                continue;
            };

            if let Some(existing) = self.get_recipe_by_uuid(&recipe.uuid)? {
                recipe_uuid_to_local_id.insert(recipe.uuid.clone(), existing.id);
                if recipe.updated_at > existing.updated_at {
                    self.conn.execute(
                        "UPDATE recipes SET food_id=?1, portions=?2, updated_at=?3 WHERE id=?4",
                        params![food_id, recipe.portions, recipe.updated_at, existing.id],
                    )?;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO recipes (food_id, portions, created_at, uuid, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)",
                    params![food_id, recipe.portions, recipe.created_at, recipe.uuid, recipe.updated_at],
                )?;
                let new_id = self.conn.last_insert_rowid();
                recipe_uuid_to_local_id.insert(recipe.uuid.clone(), new_id);
            }
        }

        // Step 4: Merge recipe ingredients
        let mut recipes_to_recompute: std::collections::HashSet<i64> =
            std::collections::HashSet::new();
        for ing in recipe_ingredients {
            if ing.uuid.is_empty() {
                continue;
            }
            let local_recipe_id = if ing.recipe_uuid.is_empty() {
                None
            } else {
                recipe_uuid_to_local_id
                    .get(&ing.recipe_uuid)
                    .copied()
                    .or_else(|| {
                        self.get_recipe_by_uuid(&ing.recipe_uuid)
                            .ok()
                            .flatten()
                            .map(|r| r.id)
                    })
            };
            let local_food_id = if ing.food_uuid.is_empty() {
                None
            } else {
                food_uuid_to_local_id
                    .get(&ing.food_uuid)
                    .copied()
                    .or_else(|| {
                        self.get_food_by_uuid(&ing.food_uuid)
                            .ok()
                            .flatten()
                            .map(|f| f.id)
                    })
            };
            let (Some(recipe_id), Some(food_id)) = (local_recipe_id, local_food_id) else {
                continue;
            };

            if let Some(existing_id) = self.get_recipe_ingredient_by_uuid(&ing.uuid)? {
                self.conn.execute(
                    "UPDATE recipe_ingredients SET recipe_id=?1, food_id=?2, quantity_g=?3 WHERE id=?4",
                    params![recipe_id, food_id, ing.quantity_g, existing_id],
                )?;
            } else {
                let now = Local::now().to_rfc3339();
                self.conn.execute(
                    "INSERT INTO recipe_ingredients (recipe_id, food_id, quantity_g, uuid, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)",
                    params![recipe_id, food_id, ing.quantity_g, ing.uuid, now],
                )?;
            }
            recipes_to_recompute.insert(recipe_id);
        }

        // Recompute virtual foods for affected recipes
        for recipe_id in &recipes_to_recompute {
            self.recompute_recipe_food(*recipe_id)?;
        }

        // Step 5: Merge targets
        for incoming_target in targets {
            let local_updated: Option<String> = self
                .conn
                .query_row(
                    "SELECT updated_at FROM targets WHERE day_of_week = ?1",
                    params![incoming_target.day_of_week],
                    |row| row.get(0),
                )
                .ok();
            let should_update = match (&incoming_target.updated_at, &local_updated) {
                (Some(incoming), Some(local)) => incoming > local,
                (Some(_), None) | (None, _) => true,
            };
            if should_update {
                let updated_at = incoming_target
                    .updated_at
                    .clone()
                    .unwrap_or_else(|| Local::now().to_rfc3339());
                self.conn.execute(
                    "INSERT OR REPLACE INTO targets (day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        incoming_target.day_of_week,
                        incoming_target.calories,
                        incoming_target.protein_pct,
                        incoming_target.carbs_pct,
                        incoming_target.fat_pct,
                        updated_at,
                    ],
                )?;
            }
        }

        // Step 6: Process tombstones
        let mut dummy_recompute = std::collections::HashSet::new();
        for tombstone in tombstones {
            self.apply_tombstone(tombstone, &mut dummy_recompute)?;
            // Store tombstone for propagation
            let exists: i64 = self
                .conn
                .query_row(
                    "SELECT COUNT(*) FROM sync_tombstones WHERE uuid = ?1 AND table_name = ?2",
                    params![tombstone.uuid, tombstone.table_name],
                    |row| row.get(0),
                )
                .unwrap_or(0);
            if exists == 0 {
                self.conn.execute(
                    "INSERT INTO sync_tombstones (uuid, table_name, deleted_at) VALUES (?1, ?2, ?3)",
                    params![tombstone.uuid, tombstone.table_name, tombstone.deleted_at],
                )?;
            }
        }

        // Step 7: Merge weight entries (LWW by date — newer updated_at wins)
        for entry in weight_entries {
            if entry.uuid.is_empty() {
                continue;
            }
            let existing: Option<(String, String)> = self
                .conn
                .query_row(
                    "SELECT uuid, updated_at FROM weight_entries WHERE date = ?1",
                    params![entry.date],
                    |row| Ok((row.get(0)?, row.get(1)?)),
                )
                .ok();
            if let Some((_existing_uuid, existing_updated)) = existing {
                if entry.updated_at > existing_updated {
                    self.conn.execute(
                        "UPDATE weight_entries SET uuid=?1, weight_kg=?2, source=?3, notes=?4, updated_at=?5 WHERE date=?6",
                        params![entry.uuid, entry.weight_kg, entry.source, entry.notes, entry.updated_at, entry.date],
                    )?;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO weight_entries (uuid, date, weight_kg, source, notes, created_at, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                    params![entry.uuid, entry.date, entry.weight_kg, entry.source, entry.notes, entry.created_at, entry.updated_at],
                )?;
            }
        }

        Ok(())
    }

    pub fn get_or_create_device_id(&self) -> Result<String> {
        let mut stmt = self
            .conn
            .prepare("SELECT value FROM config WHERE key = 'device_id'")?;
        let mut rows = stmt.query([])?;
        if let Some(row) = rows.next()? {
            return Ok(row.get(0)?);
        }
        drop(rows);
        drop(stmt);

        let device_id = Uuid::new_v4().to_string();
        self.conn.execute(
            "INSERT INTO config (key, value) VALUES ('device_id', ?1)",
            params![device_id],
        )?;
        Ok(device_id)
    }

    pub fn get_food_by_uuid(&self, uuid: &str) -> Result<Option<Food>> {
        let mut stmt = self.conn.prepare("SELECT * FROM foods WHERE uuid = ?1")?;
        let mut rows = stmt.query(params![uuid])?;
        if let Some(row) = rows.next()? {
            Ok(Some(Self::food_from_row(row)?))
        } else {
            Ok(None)
        }
    }

    fn get_meal_entry_by_uuid(&self, uuid: &str) -> Result<Option<i64>> {
        let mut stmt = self
            .conn
            .prepare("SELECT id FROM meal_entries WHERE uuid = ?1")?;
        let mut rows = stmt.query(params![uuid])?;
        if let Some(row) = rows.next()? {
            Ok(Some(row.get(0)?))
        } else {
            Ok(None)
        }
    }

    fn get_recipe_by_uuid(&self, uuid: &str) -> Result<Option<Recipe>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, uuid, food_id, portions, created_at, updated_at FROM recipes WHERE uuid = ?1",
        )?;
        let mut rows = stmt.query(params![uuid])?;
        if let Some(row) = rows.next()? {
            Ok(Some(Recipe {
                id: row.get(0)?,
                uuid: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
                food_id: row.get(2)?,
                portions: row.get(3)?,
                created_at: row.get(4)?,
                updated_at: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
            }))
        } else {
            Ok(None)
        }
    }

    fn get_recipe_ingredient_by_uuid(&self, uuid: &str) -> Result<Option<i64>> {
        let mut stmt = self
            .conn
            .prepare("SELECT id FROM recipe_ingredients WHERE uuid = ?1")?;
        let mut rows = stmt.query(params![uuid])?;
        if let Some(row) = rows.next()? {
            Ok(Some(row.get(0)?))
        } else {
            Ok(None)
        }
    }

    pub fn get_meal_entry_uuid(&self, id: i64) -> Result<Option<String>> {
        self.conn
            .query_row(
                "SELECT uuid FROM meal_entries WHERE id = ?1",
                params![id],
                |row| row.get(0),
            )
            .context("Meal entry not found")
            .map(Some)
    }

    pub fn get_recipe_uuid(&self, id: i64) -> Result<Option<String>> {
        self.conn
            .query_row(
                "SELECT uuid FROM recipes WHERE id = ?1",
                params![id],
                |row| row.get(0),
            )
            .context("Recipe not found")
            .map(Some)
    }

    pub fn get_recipe_ingredient_uuids(&self, recipe_id: i64) -> Result<Vec<String>> {
        let mut stmt = self
            .conn
            .prepare("SELECT uuid FROM recipe_ingredients WHERE recipe_id = ?1")?;
        let uuids = stmt
            .query_map(params![recipe_id], |row| row.get(0))?
            .collect::<Result<Vec<String>, _>>()?;
        Ok(uuids)
    }

    // --- Export / Import ---

    #[allow(clippy::too_many_lines)]
    pub fn export_all(&self) -> Result<ExportData> {
        let device_id = self.get_or_create_device_id()?;
        let foods = self.get_all_foods()?;
        let meal_entries = self.get_all_meal_entries_export()?;
        let recipes = self.get_all_recipes_export()?;
        let recipe_ingredients = self.get_all_recipe_ingredients_export()?;
        let targets = self.get_all_targets_export()?;
        let weight_entries = self.get_all_weight_entries_export()?;
        let tombstones = self.get_tombstones()?;

        let exported_at = Local::now().to_rfc3339();
        Ok(ExportData {
            version: 3,
            exported_at,
            device_id: Some(device_id),
            foods,
            meal_entries,
            recipes,
            recipe_ingredients,
            target: None,
            targets,
            weight_entries,
            tombstones: Some(tombstones),
        })
    }

    pub fn import_all(&self, data: &ExportData) -> Result<ImportSummary> {
        if data.version >= 2 {
            self.merge_import(data)
        } else {
            self.import_v1(data)
        }
    }

    fn import_v1(&self, data: &ExportData) -> Result<ImportSummary> {
        let foods_imported = self.import_foods(&data.foods)?;
        let meal_entries_imported = self.import_meal_entries(&data.meal_entries)?;
        let (recipes_imported, recipe_ingredients_imported) =
            self.import_recipes(&data.recipes, &data.recipe_ingredients)?;
        let targets_imported = self.import_targets(data)?;
        let weight_entries_imported = self.import_weight_entries(&data.weight_entries)?;

        Ok(ImportSummary {
            foods_imported,
            meal_entries_imported,
            recipes_imported,
            recipe_ingredients_imported,
            targets_imported,
            weight_entries_imported,
            tombstones_processed: 0,
        })
    }

    #[allow(clippy::cast_possible_wrap)]
    fn import_foods(&self, foods: &[Food]) -> Result<i64> {
        let mut count: i64 = 0;
        for food in foods {
            let exists = self
                .conn
                .query_row(
                    "SELECT COUNT(*) FROM foods WHERE id = ?1",
                    params![food.id],
                    |row| row.get::<_, i64>(0),
                )
                .unwrap_or(0);
            if exists > 0 {
                self.conn.execute(
                    "UPDATE foods SET name=?1, brand=?2, barcode=?3, calories_per_100g=?4,
                     protein_per_100g=?5, carbs_per_100g=?6, fat_per_100g=?7,
                     default_serving_g=?8, source=?9 WHERE id=?10",
                    params![
                        food.name,
                        food.brand,
                        food.barcode,
                        food.calories_per_100g,
                        food.protein_per_100g,
                        food.carbs_per_100g,
                        food.fat_per_100g,
                        food.default_serving_g,
                        food.source,
                        food.id,
                    ],
                )?;
            } else {
                self.insert_food_for_import(food)?;
            }
            count += 1;
        }
        Ok(count)
    }

    fn insert_food_for_import(&self, food: &Food) -> Result<()> {
        if let Some(barcode) = &food.barcode {
            let barcode_exists = self
                .conn
                .query_row(
                    "SELECT COUNT(*) FROM foods WHERE barcode = ?1",
                    params![barcode],
                    |row| row.get::<_, i64>(0),
                )
                .unwrap_or(0);
            if barcode_exists > 0 {
                return Ok(());
            }
        }
        self.conn.execute(
            "INSERT INTO foods (id, name, brand, barcode, calories_per_100g,
             protein_per_100g, carbs_per_100g, fat_per_100g,
             default_serving_g, source, created_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
            params![
                food.id,
                food.name,
                food.brand,
                food.barcode,
                food.calories_per_100g,
                food.protein_per_100g,
                food.carbs_per_100g,
                food.fat_per_100g,
                food.default_serving_g,
                food.source,
                food.created_at,
            ],
        )?;
        Ok(())
    }

    #[allow(clippy::cast_possible_wrap)]
    fn import_meal_entries(&self, entries: &[ExportMealEntry]) -> Result<i64> {
        let mut count: i64 = 0;
        for entry in entries {
            self.conn.execute(
                "INSERT OR REPLACE INTO meal_entries (id, date, meal_type, food_id, serving_g, display_unit, display_quantity, created_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![
                    entry.id,
                    entry.date,
                    entry.meal_type,
                    entry.food_id,
                    entry.serving_g,
                    entry.display_unit,
                    entry.display_quantity,
                    entry.created_at,
                ],
            )?;
            count += 1;
        }
        Ok(count)
    }

    #[allow(clippy::cast_possible_wrap)]
    fn import_recipes(
        &self,
        recipes: &[ExportRecipe],
        ingredients: &[ExportRecipeIngredient],
    ) -> Result<(i64, i64)> {
        let mut recipe_count: i64 = 0;
        let mut ingredient_count: i64 = 0;

        for recipe in recipes {
            self.conn.execute(
                "INSERT OR REPLACE INTO recipes (id, food_id, portions, created_at)
                 VALUES (?1, ?2, ?3, ?4)",
                params![
                    recipe.id,
                    recipe.food_id,
                    recipe.portions,
                    recipe.created_at
                ],
            )?;
            self.conn.execute(
                "DELETE FROM recipe_ingredients WHERE recipe_id = ?1",
                params![recipe.id],
            )?;
            recipe_count += 1;
        }

        for ing in ingredients {
            self.conn.execute(
                "INSERT INTO recipe_ingredients (id, recipe_id, food_id, quantity_g)
                 VALUES (?1, ?2, ?3, ?4)",
                params![ing.id, ing.recipe_id, ing.food_id, ing.quantity_g],
            )?;
            ingredient_count += 1;
        }

        Ok((recipe_count, ingredient_count))
    }

    #[allow(clippy::cast_possible_wrap)]
    fn import_targets(&self, data: &ExportData) -> Result<i64> {
        let now = Local::now().to_rfc3339();

        if !data.targets.is_empty() {
            let mut count: i64 = 0;
            for target in &data.targets {
                self.conn.execute(
                    "INSERT OR REPLACE INTO targets (day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        target.day_of_week,
                        target.calories,
                        target.protein_pct,
                        target.carbs_pct,
                        target.fat_pct,
                        now,
                    ],
                )?;
                count += 1;
            }
            Ok(count)
        } else if let Some(legacy) = &data.target {
            // Legacy single target — apply to all 7 days
            for day in 0..7_i64 {
                self.conn.execute(
                    "INSERT OR REPLACE INTO targets (day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        day,
                        legacy.calories,
                        legacy.protein_pct,
                        legacy.carbs_pct,
                        legacy.fat_pct,
                        now,
                    ],
                )?;
            }
            Ok(7)
        } else {
            Ok(0)
        }
    }

    #[allow(clippy::cast_possible_wrap)]
    fn import_weight_entries(&self, entries: &[ExportWeightEntry]) -> Result<i64> {
        let mut count: i64 = 0;
        for entry in entries {
            self.conn.execute(
                "INSERT OR REPLACE INTO weight_entries (uuid, date, weight_kg, source, notes, created_at, updated_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                params![
                    entry.uuid,
                    entry.date,
                    entry.weight_kg,
                    entry.source,
                    entry.notes,
                    entry.created_at,
                    entry.updated_at,
                ],
            )?;
            count += 1;
        }
        Ok(count)
    }

    #[allow(clippy::cast_possible_wrap, clippy::too_many_lines)]
    fn merge_import(&self, data: &ExportData) -> Result<ImportSummary> {
        let mut foods_imported: i64 = 0;
        let mut meal_entries_imported: i64 = 0;
        let mut recipes_imported: i64 = 0;
        let mut recipe_ingredients_imported: i64 = 0;
        let mut tombstones_processed: i64 = 0;

        // Step 1: Merge foods — build uuid→local_id mapping
        let mut food_uuid_to_local_id: HashMap<String, i64> = HashMap::new();
        for food in &data.foods {
            if food.uuid.is_empty() {
                continue;
            }
            if let Some(existing) = self.get_food_by_uuid(&food.uuid)? {
                food_uuid_to_local_id.insert(food.uuid.clone(), existing.id);
                if food.updated_at > existing.updated_at {
                    self.conn.execute(
                        "UPDATE foods SET name=?1, brand=?2, barcode=?3, calories_per_100g=?4,
                         protein_per_100g=?5, carbs_per_100g=?6, fat_per_100g=?7,
                         default_serving_g=?8, source=?9, updated_at=?10 WHERE uuid=?11",
                        params![
                            food.name,
                            food.brand,
                            food.barcode,
                            food.calories_per_100g,
                            food.protein_per_100g,
                            food.carbs_per_100g,
                            food.fat_per_100g,
                            food.default_serving_g,
                            food.source,
                            food.updated_at,
                            food.uuid,
                        ],
                    )?;
                    foods_imported += 1;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO foods (name, brand, barcode, calories_per_100g,
                     protein_per_100g, carbs_per_100g, fat_per_100g,
                     default_serving_g, source, created_at, uuid, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                    params![
                        food.name,
                        food.brand,
                        food.barcode,
                        food.calories_per_100g,
                        food.protein_per_100g,
                        food.carbs_per_100g,
                        food.fat_per_100g,
                        food.default_serving_g,
                        food.source,
                        food.created_at,
                        food.uuid,
                        food.updated_at,
                    ],
                )?;
                let new_id = self.conn.last_insert_rowid();
                food_uuid_to_local_id.insert(food.uuid.clone(), new_id);
                foods_imported += 1;
            }
        }

        // Step 2: Merge meal entries
        for entry in &data.meal_entries {
            if entry.uuid.is_empty() {
                continue;
            }
            let local_food_id = if entry.food_uuid.is_empty() {
                None
            } else {
                food_uuid_to_local_id.get(&entry.food_uuid).copied()
            };
            let Some(food_id) = local_food_id else {
                continue;
            };

            if let Some(existing_id) = self.get_meal_entry_by_uuid(&entry.uuid)? {
                let existing_updated: String = self.conn.query_row(
                    "SELECT COALESCE(updated_at, '') FROM meal_entries WHERE id = ?1",
                    params![existing_id],
                    |row| row.get(0),
                )?;
                if entry.updated_at > existing_updated {
                    self.conn.execute(
                        "UPDATE meal_entries SET date=?1, meal_type=?2, food_id=?3, serving_g=?4, display_unit=?5, display_quantity=?6, updated_at=?7 WHERE id=?8",
                        params![entry.date, entry.meal_type, food_id, entry.serving_g, entry.display_unit, entry.display_quantity, entry.updated_at, existing_id],
                    )?;
                    meal_entries_imported += 1;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO meal_entries (date, meal_type, food_id, serving_g, display_unit, display_quantity, created_at, uuid, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
                    params![entry.date, entry.meal_type, food_id, entry.serving_g, entry.display_unit, entry.display_quantity, entry.created_at, entry.uuid, entry.updated_at],
                )?;
                meal_entries_imported += 1;
            }
        }

        // Step 3: Merge recipes — build recipe_uuid→local_id mapping
        let mut recipe_uuid_to_local_id: HashMap<String, i64> = HashMap::new();
        for recipe in &data.recipes {
            if recipe.uuid.is_empty() {
                continue;
            }
            let local_food_id = if recipe.food_uuid.is_empty() {
                None
            } else {
                food_uuid_to_local_id.get(&recipe.food_uuid).copied()
            };
            let Some(food_id) = local_food_id else {
                continue;
            };

            if let Some(existing) = self.get_recipe_by_uuid(&recipe.uuid)? {
                recipe_uuid_to_local_id.insert(recipe.uuid.clone(), existing.id);
                if recipe.updated_at > existing.updated_at {
                    self.conn.execute(
                        "UPDATE recipes SET food_id=?1, portions=?2, updated_at=?3 WHERE id=?4",
                        params![food_id, recipe.portions, recipe.updated_at, existing.id],
                    )?;
                    recipes_imported += 1;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO recipes (food_id, portions, created_at, uuid, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)",
                    params![food_id, recipe.portions, recipe.created_at, recipe.uuid, recipe.updated_at],
                )?;
                let new_id = self.conn.last_insert_rowid();
                recipe_uuid_to_local_id.insert(recipe.uuid.clone(), new_id);
                recipes_imported += 1;
            }
        }

        // Step 4: Merge recipe ingredients
        let mut recipes_to_recompute: std::collections::HashSet<i64> =
            std::collections::HashSet::new();
        for ing in &data.recipe_ingredients {
            if ing.uuid.is_empty() {
                continue;
            }
            let local_recipe_id = if ing.recipe_uuid.is_empty() {
                None
            } else {
                recipe_uuid_to_local_id.get(&ing.recipe_uuid).copied()
            };
            let local_food_id = if ing.food_uuid.is_empty() {
                None
            } else {
                food_uuid_to_local_id.get(&ing.food_uuid).copied()
            };
            let (Some(recipe_id), Some(food_id)) = (local_recipe_id, local_food_id) else {
                continue;
            };

            if let Some(existing_id) = self.get_recipe_ingredient_by_uuid(&ing.uuid)? {
                self.conn.execute(
                    "UPDATE recipe_ingredients SET recipe_id=?1, food_id=?2, quantity_g=?3 WHERE id=?4",
                    params![recipe_id, food_id, ing.quantity_g, existing_id],
                )?;
                recipe_ingredients_imported += 1;
            } else {
                let now = Local::now().to_rfc3339();
                self.conn.execute(
                    "INSERT INTO recipe_ingredients (recipe_id, food_id, quantity_g, uuid, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)",
                    params![recipe_id, food_id, ing.quantity_g, ing.uuid, now],
                )?;
                recipe_ingredients_imported += 1;
            }
            recipes_to_recompute.insert(recipe_id);
        }

        // Recompute virtual foods for affected recipes
        for recipe_id in &recipes_to_recompute {
            self.recompute_recipe_food(*recipe_id)?;
        }

        // Step 5: Merge targets
        let mut targets_imported: i64 = 0;
        // Determine the list of targets to merge
        let targets_to_merge: Vec<ExportTarget> = if !data.targets.is_empty() {
            data.targets.clone()
        } else if let Some(legacy) = &data.target {
            // Legacy single target — expand to all 7 days
            (0..7_i64)
                .map(|day| ExportTarget {
                    day_of_week: day,
                    calories: legacy.calories,
                    protein_pct: legacy.protein_pct,
                    carbs_pct: legacy.carbs_pct,
                    fat_pct: legacy.fat_pct,
                    updated_at: legacy.updated_at.clone(),
                })
                .collect()
        } else {
            Vec::new()
        };
        for incoming_target in &targets_to_merge {
            let local_updated: Option<String> = self
                .conn
                .query_row(
                    "SELECT updated_at FROM targets WHERE day_of_week = ?1",
                    params![incoming_target.day_of_week],
                    |row| row.get(0),
                )
                .ok();
            let should_update = match (&incoming_target.updated_at, &local_updated) {
                (Some(incoming), Some(local)) => incoming > local,
                (Some(_), None) | (None, _) => true,
            };
            if should_update {
                let updated_at = incoming_target
                    .updated_at
                    .clone()
                    .unwrap_or_else(|| Local::now().to_rfc3339());
                self.conn.execute(
                    "INSERT OR REPLACE INTO targets (day_of_week, calories, protein_pct, carbs_pct, fat_pct, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        incoming_target.day_of_week,
                        incoming_target.calories,
                        incoming_target.protein_pct,
                        incoming_target.carbs_pct,
                        incoming_target.fat_pct,
                        updated_at,
                    ],
                )?;
                targets_imported += 1;
            }
        }

        // Step 6: Process tombstones — delete local records if older than tombstone
        if let Some(tombstones) = &data.tombstones {
            for tombstone in tombstones {
                let deleted = self.apply_tombstone(tombstone, &mut recipes_to_recompute)?;
                if deleted {
                    tombstones_processed += 1;
                }
            }
        }

        // Step 7: Store incoming tombstones locally for propagation
        if let Some(tombstones) = &data.tombstones {
            for tombstone in tombstones {
                let exists: i64 = self
                    .conn
                    .query_row(
                        "SELECT COUNT(*) FROM sync_tombstones WHERE uuid = ?1 AND table_name = ?2",
                        params![tombstone.uuid, tombstone.table_name],
                        |row| row.get(0),
                    )
                    .unwrap_or(0);
                if exists == 0 {
                    self.conn.execute(
                        "INSERT INTO sync_tombstones (uuid, table_name, deleted_at) VALUES (?1, ?2, ?3)",
                        params![tombstone.uuid, tombstone.table_name, tombstone.deleted_at],
                    )?;
                }
            }
        }

        // Recompute any recipes affected by tombstone ingredient deletions
        for recipe_id in recipes_to_recompute {
            if self.get_recipe_by_id(recipe_id).is_ok() {
                self.recompute_recipe_food(recipe_id)?;
            }
        }

        // Step 8: Merge weight entries (LWW by date — newer updated_at wins)
        let mut weight_entries_imported: i64 = 0;
        for entry in &data.weight_entries {
            if entry.uuid.is_empty() {
                continue;
            }
            let existing: Option<(String, String)> = self
                .conn
                .query_row(
                    "SELECT uuid, updated_at FROM weight_entries WHERE date = ?1",
                    params![entry.date],
                    |row| Ok((row.get(0)?, row.get(1)?)),
                )
                .ok();
            if let Some((_existing_uuid, existing_updated)) = existing {
                if entry.updated_at > existing_updated {
                    self.conn.execute(
                        "UPDATE weight_entries SET uuid=?1, weight_kg=?2, source=?3, notes=?4, updated_at=?5 WHERE date=?6",
                        params![entry.uuid, entry.weight_kg, entry.source, entry.notes, entry.updated_at, entry.date],
                    )?;
                    weight_entries_imported += 1;
                }
            } else {
                self.conn.execute(
                    "INSERT INTO weight_entries (uuid, date, weight_kg, source, notes, created_at, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                    params![entry.uuid, entry.date, entry.weight_kg, entry.source, entry.notes, entry.created_at, entry.updated_at],
                )?;
                weight_entries_imported += 1;
            }
        }

        Ok(ImportSummary {
            foods_imported,
            meal_entries_imported,
            recipes_imported,
            recipe_ingredients_imported,
            targets_imported,
            weight_entries_imported,
            tombstones_processed,
        })
    }

    fn apply_tombstone(
        &self,
        tombstone: &SyncTombstone,
        recipes_to_recompute: &mut std::collections::HashSet<i64>,
    ) -> Result<bool> {
        match tombstone.table_name.as_str() {
            "foods" => {
                if let Some(food) = self.get_food_by_uuid(&tombstone.uuid)? {
                    if food.updated_at < tombstone.deleted_at {
                        self.conn.execute(
                            "DELETE FROM foods WHERE uuid = ?1",
                            params![tombstone.uuid],
                        )?;
                        return Ok(true);
                    }
                }
                Ok(false)
            }
            "meal_entries" => {
                let local: Option<(i64, String)> = self
                    .conn
                    .query_row(
                        "SELECT id, COALESCE(updated_at, '') FROM meal_entries WHERE uuid = ?1",
                        params![tombstone.uuid],
                        |row| Ok((row.get(0)?, row.get(1)?)),
                    )
                    .ok();
                if let Some((id, updated_at)) = local {
                    if updated_at < tombstone.deleted_at {
                        self.conn
                            .execute("DELETE FROM meal_entries WHERE id = ?1", params![id])?;
                        return Ok(true);
                    }
                }
                Ok(false)
            }
            "recipes" => {
                if let Some(recipe) = self.get_recipe_by_uuid(&tombstone.uuid)? {
                    if recipe.updated_at < tombstone.deleted_at {
                        self.conn.execute(
                            "DELETE FROM recipe_ingredients WHERE recipe_id = ?1",
                            params![recipe.id],
                        )?;
                        self.conn
                            .execute("DELETE FROM recipes WHERE id = ?1", params![recipe.id])?;
                        self.conn
                            .execute("DELETE FROM foods WHERE id = ?1", params![recipe.food_id])?;
                        return Ok(true);
                    }
                }
                Ok(false)
            }
            "recipe_ingredients" => {
                let local: Option<(i64, String, i64)> = self
                    .conn
                    .query_row(
                        "SELECT id, COALESCE(updated_at, ''), recipe_id FROM recipe_ingredients WHERE uuid = ?1",
                        params![tombstone.uuid],
                        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
                    )
                    .ok();
                if let Some((id, updated_at, recipe_id)) = local {
                    if updated_at < tombstone.deleted_at {
                        self.conn
                            .execute("DELETE FROM recipe_ingredients WHERE id = ?1", params![id])?;
                        recipes_to_recompute.insert(recipe_id);
                        return Ok(true);
                    }
                }
                Ok(false)
            }
            _ => Ok(false),
        }
    }

    // --- Weight Entries ---

    pub fn upsert_weight(&self, entry: &NewWeightEntry) -> Result<WeightEntry> {
        let now = Local::now().to_rfc3339();
        let uuid = Uuid::new_v4().to_string();
        let date_str = entry.date.format("%Y-%m-%d").to_string();
        self.conn.execute(
            "INSERT INTO weight_entries (uuid, date, weight_kg, source, notes, created_at, updated_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
             ON CONFLICT(date) DO UPDATE SET
                weight_kg = excluded.weight_kg,
                source = excluded.source,
                notes = excluded.notes,
                updated_at = excluded.updated_at",
            params![uuid, date_str, entry.weight_kg, entry.source, entry.notes, now, now],
        )?;
        self.get_weight(entry.date)?
            .context("Weight entry not found after upsert")
    }

    pub fn get_weight(&self, date: NaiveDate) -> Result<Option<WeightEntry>> {
        let date_str = date.format("%Y-%m-%d").to_string();
        let mut stmt = self.conn.prepare(
            "SELECT id, uuid, date, weight_kg, source, notes, created_at, updated_at
             FROM weight_entries WHERE date = ?1",
        )?;
        let mut rows = stmt.query(params![date_str])?;
        if let Some(row) = rows.next()? {
            Ok(Some(Self::weight_entry_from_row(row)?))
        } else {
            Ok(None)
        }
    }

    pub fn get_weight_history(&self, days: Option<i64>) -> Result<Vec<WeightEntry>> {
        let query = match days {
            Some(n) => format!(
                "SELECT id, uuid, date, weight_kg, source, notes, created_at, updated_at
                 FROM weight_entries ORDER BY date DESC LIMIT {n}"
            ),
            None => "SELECT id, uuid, date, weight_kg, source, notes, created_at, updated_at
                     FROM weight_entries ORDER BY date DESC"
                .to_string(),
        };
        let mut stmt = self.conn.prepare(&query)?;
        let entries = stmt
            .query_map([], Self::weight_entry_from_row)?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(entries)
    }

    pub fn delete_weight(&self, id: i64) -> Result<()> {
        let rows = self
            .conn
            .execute("DELETE FROM weight_entries WHERE id = ?1", params![id])?;
        if rows == 0 {
            anyhow::bail!("Weight entry not found");
        }
        Ok(())
    }

    fn weight_entry_from_row(row: &rusqlite::Row) -> rusqlite::Result<WeightEntry> {
        let date_str: String = row.get(2)?;
        let date = NaiveDate::parse_from_str(&date_str, "%Y-%m-%d")
            .unwrap_or_else(|_| NaiveDate::from_ymd_opt(2000, 1, 1).expect("valid date"));
        Ok(WeightEntry {
            id: row.get(0)?,
            uuid: row.get(1)?,
            date,
            weight_kg: row.get(3)?,
            source: row.get(4)?,
            notes: row.get(5)?,
            created_at: row.get(6)?,
            updated_at: row.get(7)?,
        })
    }

    // --- UX Queries ---

    pub fn get_recently_logged_foods(&self, limit: i64) -> Result<Vec<RecentFood>> {
        let mut stmt = self.conn.prepare(
            "SELECT f.id, f.name, f.brand, f.barcode, f.calories_per_100g,
                    f.protein_per_100g, f.carbs_per_100g, f.fat_per_100g,
                    f.default_serving_g, f.source, f.created_at, f.uuid, f.updated_at,
                    latest.last_serving_g, latest.last_meal_type,
                    counts.log_count, counts.last_date
             FROM foods f
             JOIN (
                 SELECT food_id, COUNT(*) as log_count, MAX(date) as last_date
                 FROM meal_entries
                 GROUP BY food_id
             ) counts ON f.id = counts.food_id
             JOIN (
                 SELECT me.food_id, me.serving_g as last_serving_g, me.meal_type as last_meal_type
                 FROM meal_entries me
                 INNER JOIN (
                     SELECT food_id, MAX(id) as max_id
                     FROM meal_entries
                     WHERE (food_id, date) IN (
                         SELECT food_id, MAX(date) FROM meal_entries GROUP BY food_id
                     )
                     GROUP BY food_id
                 ) latest_ids ON me.id = latest_ids.max_id
             ) latest ON f.id = latest.food_id
             ORDER BY counts.last_date DESC, counts.log_count DESC
             LIMIT ?1",
        )?;
        let foods = stmt
            .query_map(params![limit], |row| {
                let food = Self::food_from_row(row)?;
                Ok(RecentFood {
                    food,
                    last_serving_g: row.get(13)?,
                    last_meal_type: row.get(14)?,
                    log_count: row.get(15)?,
                    last_logged: row.get(16)?,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;
        Ok(foods)
    }

    pub fn get_logging_streak(&self, today: NaiveDate) -> Result<i64> {
        // Get distinct dates with meal entries, ordered DESC
        let mut stmt = self
            .conn
            .prepare("SELECT DISTINCT date FROM meal_entries ORDER BY date DESC")?;
        let dates: Vec<String> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        if dates.is_empty() {
            return Ok(0);
        }

        let today_str = today.format("%Y-%m-%d").to_string();
        let yesterday = today - chrono::Duration::days(1);
        let yesterday_str = yesterday.format("%Y-%m-%d").to_string();

        // Determine starting point: today or yesterday
        let start_date = if dates.first().is_some_and(|d| d == &today_str) {
            today
        } else if dates.first().is_some_and(|d| d == &yesterday_str) {
            yesterday
        } else {
            return Ok(0);
        };

        let mut streak: i64 = 0;
        for date_str in &dates {
            let expected = (start_date - chrono::Duration::days(streak))
                .format("%Y-%m-%d")
                .to_string();
            if date_str == &expected {
                streak += 1;
            } else {
                break;
            }
        }

        Ok(streak)
    }

    #[allow(clippy::cast_precision_loss)]
    pub fn get_calorie_average(&self, days: i64) -> Result<f64> {
        let today = Local::now().date_naive();
        let start_date = today - chrono::Duration::days(days - 1);
        let start_str = start_date.format("%Y-%m-%d").to_string();
        let end_str = today.format("%Y-%m-%d").to_string();

        let result: Option<f64> = self.conn.query_row(
            "SELECT AVG(daily_total) FROM (
                SELECT SUM(f.calories_per_100g * me.serving_g / 100.0) as daily_total
                FROM meal_entries me
                JOIN foods f ON me.food_id = f.id
                WHERE me.date >= ?1 AND me.date <= ?2
                GROUP BY me.date
            )",
            params![start_str, end_str],
            |row| row.get(0),
        )?;

        Ok(result.unwrap_or(0.0))
    }

    // --- User Settings ---

    pub fn set_setting(&self, key: &str, value: &str) -> Result<()> {
        let now = Local::now().to_rfc3339();
        self.conn.execute(
            "INSERT INTO user_settings (key, value, updated_at)
             VALUES (?1, ?2, ?3)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
            params![key, value, now],
        )?;
        Ok(())
    }

    pub fn get_setting(&self, key: &str) -> Result<Option<String>> {
        let mut stmt = self
            .conn
            .prepare("SELECT value FROM user_settings WHERE key = ?1")?;
        let mut rows = stmt.query(params![key])?;
        if let Some(row) = rows.next()? {
            Ok(Some(row.get(0)?))
        } else {
            Ok(None)
        }
    }

    pub fn delete_setting(&self, key: &str) -> Result<bool> {
        let rows = self
            .conn
            .execute("DELETE FROM user_settings WHERE key = ?1", params![key])?;
        Ok(rows > 0)
    }

    pub fn build_daily_summary(&self, date: NaiveDate) -> Result<DailySummary> {
        let entries = self.get_entries_for_date(date)?;
        let mut meals: Vec<MealGroup> = Vec::new();

        for meal_type in MEAL_TYPES {
            let meal_entries: Vec<MealEntry> = entries
                .iter()
                .filter(|e| e.meal_type == *meal_type)
                .cloned()
                .collect();

            if meal_entries.is_empty() {
                continue;
            }

            let subtotal_calories: f64 = meal_entries.iter().filter_map(|e| e.calories).sum();
            let subtotal_protein: f64 = meal_entries.iter().filter_map(|e| e.protein).sum();
            let subtotal_carbs: f64 = meal_entries.iter().filter_map(|e| e.carbs).sum();
            let subtotal_fat: f64 = meal_entries.iter().filter_map(|e| e.fat).sum();

            meals.push(MealGroup {
                meal_type: meal_type.to_string(),
                entries: meal_entries,
                subtotal_calories,
                subtotal_protein,
                subtotal_carbs,
                subtotal_fat,
            });
        }

        let total_calories: f64 = meals.iter().map(|m| m.subtotal_calories).sum();
        let total_protein: f64 = meals.iter().map(|m| m.subtotal_protein).sum();
        let total_carbs: f64 = meals.iter().map(|m| m.subtotal_carbs).sum();
        let total_fat: f64 = meals.iter().map(|m| m.subtotal_fat).sum();

        let day_of_week = i64::from(date.weekday().num_days_from_monday());
        let target = self.get_target(day_of_week)?;

        Ok(DailySummary {
            date: date.format("%Y-%m-%d").to_string(),
            meals,
            total_calories,
            total_protein,
            total_carbs,
            total_fat,
            target,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{NewFood, NewMealEntry, UpdateMealEntry};

    fn sample_food() -> NewFood {
        NewFood {
            name: "Chicken Breast".to_string(),
            brand: Some("Acme".to_string()),
            barcode: Some("1234567890".to_string()),
            calories_per_100g: 165.0,
            protein_per_100g: Some(31.0),
            carbs_per_100g: Some(0.0),
            fat_per_100g: Some(3.6),
            default_serving_g: Some(150.0),
            source: "manual".to_string(),
        }
    }

    #[test]
    fn test_insert_and_get_food() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        assert_eq!(food.name, "Chicken Breast");
        assert_eq!(food.brand.as_deref(), Some("Acme"));
        assert_eq!(food.barcode.as_deref(), Some("1234567890"));
        assert_eq!(food.calories_per_100g, 165.0);
        assert_eq!(food.protein_per_100g, Some(31.0));
        assert_eq!(food.source, "manual");

        let fetched = db.get_food_by_id(food.id).unwrap();
        assert_eq!(fetched.id, food.id);
        assert_eq!(fetched.name, "Chicken Breast");
    }

    #[test]
    fn test_upsert_food_by_barcode() {
        let db = Database::open_in_memory().unwrap();
        let food1 = db.upsert_food_by_barcode(&sample_food()).unwrap();
        let food2 = db.upsert_food_by_barcode(&sample_food()).unwrap();

        // Should return the same food (dedup by barcode)
        assert_eq!(food1.id, food2.id);
    }

    #[test]
    fn test_search_foods_local() {
        let db = Database::open_in_memory().unwrap();
        db.insert_food(&sample_food()).unwrap();
        db.insert_food(&NewFood {
            name: "Brown Rice".to_string(),
            brand: None,
            barcode: None,
            calories_per_100g: 112.0,
            protein_per_100g: Some(2.6),
            carbs_per_100g: Some(23.5),
            fat_per_100g: Some(0.9),
            default_serving_g: None,
            source: "manual".to_string(),
        })
        .unwrap();

        let results = db.search_foods_local("chicken").unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "Chicken Breast");

        let results = db.search_foods_local("rice").unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "Brown Rice");

        let results = db.search_foods_local("pizza").unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn test_list_foods() {
        let db = Database::open_in_memory().unwrap();
        db.insert_food(&sample_food()).unwrap();
        db.insert_food(&NewFood {
            name: "Brown Rice".to_string(),
            brand: None,
            barcode: None,
            calories_per_100g: 112.0,
            protein_per_100g: None,
            carbs_per_100g: None,
            fat_per_100g: None,
            default_serving_g: None,
            source: "manual".to_string(),
        })
        .unwrap();

        // List all
        let all = db.list_foods(None).unwrap();
        assert_eq!(all.len(), 2);

        // List with filter
        let filtered = db.list_foods(Some("rice")).unwrap();
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].name, "Brown Rice");
    }

    #[test]
    fn test_insert_and_get_meal_entry() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 200.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        assert_eq!(entry.meal_type, "lunch");
        assert_eq!(entry.serving_g, 200.0);
        assert_eq!(entry.food_name.as_deref(), Some("Chicken Breast"));
        // 165 cal/100g * 200g / 100 = 330 kcal
        let cal = entry.calories.unwrap();
        assert!((cal - 330.0).abs() < 0.01);
        // 31 protein/100g * 200/100 = 62
        let pro = entry.protein.unwrap();
        assert!((pro - 62.0).abs() < 0.01);
    }

    #[test]
    fn test_delete_meal_entry() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        assert!(db.delete_meal_entry(entry.id).unwrap());
        // Deleting again should return false
        assert!(!db.delete_meal_entry(entry.id).unwrap());
    }

    #[test]
    fn test_get_entries_for_date() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let date1 = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        let date2 = NaiveDate::from_ymd_opt(2024, 6, 16).unwrap();

        db.insert_meal_entry(&NewMealEntry {
            date: date1,
            meal_type: "breakfast".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();
        db.insert_meal_entry(&NewMealEntry {
            date: date2,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 150.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let entries = db.get_entries_for_date(date1).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].meal_type, "breakfast");

        let entries = db.get_entries_for_date(date2).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].meal_type, "lunch");
    }

    #[test]
    fn test_get_entries_for_date_and_meal() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        db.insert_meal_entry(&NewMealEntry {
            date,
            meal_type: "breakfast".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();
        db.insert_meal_entry(&NewMealEntry {
            date,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let breakfast = db.get_entries_for_date_and_meal(date, "breakfast").unwrap();
        assert_eq!(breakfast.len(), 1);
        assert_eq!(breakfast[0].serving_g, 100.0);

        let lunch = db.get_entries_for_date_and_meal(date, "lunch").unwrap();
        assert_eq!(lunch.len(), 1);
        assert_eq!(lunch[0].serving_g, 200.0);

        let dinner = db.get_entries_for_date_and_meal(date, "dinner").unwrap();
        assert!(dinner.is_empty());
    }

    #[test]
    fn test_build_daily_summary() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        // Breakfast: 100g -> 165 kcal
        db.insert_meal_entry(&NewMealEntry {
            date,
            meal_type: "breakfast".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();
        // Lunch: 200g -> 330 kcal
        db.insert_meal_entry(&NewMealEntry {
            date,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let summary = db.build_daily_summary(date).unwrap();
        assert_eq!(summary.meals.len(), 2);
        assert_eq!(summary.meals[0].meal_type, "breakfast");
        assert_eq!(summary.meals[1].meal_type, "lunch");
        assert!((summary.meals[0].subtotal_calories - 165.0).abs() < 0.01);
        assert!((summary.meals[1].subtotal_calories - 330.0).abs() < 0.01);
        assert!((summary.total_calories - 495.0).abs() < 0.01);
        assert!((summary.total_protein - 93.0).abs() < 0.01); // 31*1 + 31*2
    }

    #[test]
    fn test_build_daily_summary_empty() {
        let db = Database::open_in_memory().unwrap();
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        let summary = db.build_daily_summary(date).unwrap();
        assert!(summary.meals.is_empty());
        assert_eq!(summary.total_calories, 0.0);
        assert_eq!(summary.total_protein, 0.0);
        assert_eq!(summary.total_carbs, 0.0);
        assert_eq!(summary.total_fat, 0.0);
        assert!(summary.target.is_none());
    }

    #[test]
    fn test_set_and_get_target() {
        let db = Database::open_in_memory().unwrap();

        // No target initially
        assert!(db.get_target(0).unwrap().is_none());

        // Set target with macros for Monday (0)
        let target = db
            .set_target(0, 1800, Some(40), Some(30), Some(30))
            .unwrap();
        assert_eq!(target.day_of_week, 0);
        assert_eq!(target.calories, 1800);
        assert_eq!(target.protein_pct, Some(40));
        assert!((target.protein_g.unwrap() - 180.0).abs() < 0.01);
        assert!((target.carbs_g.unwrap() - 135.0).abs() < 0.01);
        assert!((target.fat_g.unwrap() - 60.0).abs() < 0.01);

        // Read it back
        let fetched = db.get_target(0).unwrap().unwrap();
        assert_eq!(fetched.calories, 1800);
        assert_eq!(fetched.protein_pct, Some(40));

        // Different day should have no target
        assert!(db.get_target(1).unwrap().is_none());

        // Set a different day
        let sat = db.set_target(5, 2200, None, None, None).unwrap();
        assert_eq!(sat.day_of_week, 5);
        assert_eq!(sat.calories, 2200);

        // Update Monday (replace)
        let updated = db.set_target(0, 2000, None, None, None).unwrap();
        assert_eq!(updated.calories, 2000);
        assert!(updated.protein_pct.is_none());

        // Monday should be updated
        let fetched = db.get_target(0).unwrap().unwrap();
        assert_eq!(fetched.calories, 2000);

        // get_all_targets should return both
        let all = db.get_all_targets().unwrap();
        assert_eq!(all.len(), 2);
        assert_eq!(all[0].day_of_week, 0);
        assert_eq!(all[1].day_of_week, 5);
    }

    #[test]
    fn test_clear_target() {
        let db = Database::open_in_memory().unwrap();

        // Clear when nothing set
        assert!(!db.clear_target(0).unwrap());

        // Set targets for Mon and Tue
        db.set_target(0, 1800, None, None, None).unwrap();
        db.set_target(1, 1900, None, None, None).unwrap();
        assert!(db.get_target(0).unwrap().is_some());
        assert!(db.get_target(1).unwrap().is_some());

        // Clear Monday only
        assert!(db.clear_target(0).unwrap());
        assert!(db.get_target(0).unwrap().is_none());
        assert!(db.get_target(1).unwrap().is_some());

        // Clear all
        db.set_target(0, 1800, None, None, None).unwrap();
        assert!(db.clear_all_targets().unwrap());
        assert!(db.get_all_targets().unwrap().is_empty());

        // Clear all when empty
        assert!(!db.clear_all_targets().unwrap());
    }

    #[test]
    fn test_summary_includes_target() {
        let db = Database::open_in_memory().unwrap();
        // 2024-06-15 is a Saturday = day_of_week 5
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        // No target
        let summary = db.build_daily_summary(date).unwrap();
        assert!(summary.target.is_none());

        // Set target for Saturday (5)
        db.set_target(5, 1800, Some(40), Some(30), Some(30))
            .unwrap();
        let summary = db.build_daily_summary(date).unwrap();
        let target = summary.target.unwrap();
        assert_eq!(target.calories, 1800);
        assert_eq!(target.day_of_week, 5);
        assert!((target.protein_g.unwrap() - 180.0).abs() < 0.01);

        // Monday target should NOT appear for Saturday
        db.set_target(0, 2500, None, None, None).unwrap();
        let summary = db.build_daily_summary(date).unwrap();
        let target = summary.target.unwrap();
        assert_eq!(target.calories, 1800); // still Saturday's target
    }

    #[test]
    fn test_update_meal_entry_serving() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        let updated = db
            .update_meal_entry(
                entry.id,
                &UpdateMealEntry {
                    serving_g: Some(250.0),
                    meal_type: None,
                    date: None,
                    display_unit: None,
                    display_quantity: None,
                },
            )
            .unwrap();

        assert_eq!(updated.serving_g, 250.0);
        assert_eq!(updated.meal_type, "lunch");
        // 165 * 250 / 100 = 412.5
        assert!((updated.calories.unwrap() - 412.5).abs() < 0.01);
    }

    #[test]
    fn test_update_meal_entry_meal_type() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        let updated = db
            .update_meal_entry(
                entry.id,
                &UpdateMealEntry {
                    serving_g: None,
                    meal_type: Some("dinner".to_string()),
                    date: None,
                    display_unit: None,
                    display_quantity: None,
                },
            )
            .unwrap();

        assert_eq!(updated.meal_type, "dinner");
        assert_eq!(updated.serving_g, 100.0);
    }

    #[test]
    fn test_update_meal_entry_not_found() {
        let db = Database::open_in_memory().unwrap();
        let result = db.update_meal_entry(
            999,
            &UpdateMealEntry {
                serving_g: Some(100.0),
                meal_type: None,
                date: None,
                display_unit: None,
                display_quantity: None,
            },
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_update_meal_entry_noop() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        let updated = db
            .update_meal_entry(
                entry.id,
                &UpdateMealEntry {
                    serving_g: None,
                    meal_type: None,
                    date: None,
                    display_unit: None,
                    display_quantity: None,
                },
            )
            .unwrap();

        assert_eq!(updated.serving_g, 100.0);
        assert_eq!(updated.meal_type, "lunch");
    }

    // --- Recipe tests ---

    fn sample_ingredient_rice() -> NewFood {
        NewFood {
            name: "Brown Rice".to_string(),
            brand: None,
            barcode: None,
            calories_per_100g: 112.0,
            protein_per_100g: Some(2.6),
            carbs_per_100g: Some(23.5),
            fat_per_100g: Some(0.9),
            default_serving_g: None,
            source: "manual".to_string(),
        }
    }

    #[test]
    fn test_create_recipe() {
        let db = Database::open_in_memory().unwrap();
        let recipe = db.create_recipe("Chicken and Rice", 4.0).unwrap();
        assert_eq!(recipe.portions, 4.0);

        // Virtual food should exist
        let food = db.get_food_by_id(recipe.food_id).unwrap();
        assert_eq!(food.name, "Chicken and Rice");
        assert_eq!(food.source, "recipe");
    }

    #[test]
    fn test_recipe_add_ingredient_recomputes() {
        let db = Database::open_in_memory().unwrap();
        let chicken = db.insert_food(&sample_food()).unwrap();
        let rice = db.insert_food(&sample_ingredient_rice()).unwrap();
        let recipe = db.create_recipe("Chicken and Rice", 2.0).unwrap();

        // Add 200g chicken: 165 cal/100g -> 330 cal total
        db.add_recipe_ingredient(recipe.id, chicken.id, 200.0)
            .unwrap();
        // Add 300g rice: 112 cal/100g -> 336 cal total
        db.add_recipe_ingredient(recipe.id, rice.id, 300.0).unwrap();

        let detail = db.get_recipe_detail(recipe.id).unwrap();
        assert_eq!(detail.ingredients.len(), 2);
        assert!((detail.total_weight_g - 500.0).abs() < 0.01);
        assert!((detail.per_portion_g - 250.0).abs() < 0.01);

        // Total cal = 330 + 336 = 666
        let expected_total_cal = 330.0 + 336.0;
        let expected_per_portion_cal = expected_total_cal / 2.0;
        assert!((detail.per_portion_calories - expected_per_portion_cal).abs() < 0.01);

        // Virtual food per-100g should be recomputed
        let food = db.get_food_by_id(recipe.food_id).unwrap();
        let expected_cal_100 = expected_total_cal * 100.0 / 500.0;
        assert!((food.calories_per_100g - expected_cal_100).abs() < 0.01);
        // default_serving_g = total_weight / portions = 500/2 = 250
        assert!((food.default_serving_g.unwrap() - 250.0).abs() < 0.01);
    }

    #[test]
    fn test_recipe_set_portions() {
        let db = Database::open_in_memory().unwrap();
        let chicken = db.insert_food(&sample_food()).unwrap();
        let recipe = db.create_recipe("Just Chicken", 2.0).unwrap();
        db.add_recipe_ingredient(recipe.id, chicken.id, 400.0)
            .unwrap();

        // Change to 4 portions
        db.set_recipe_portions(recipe.id, 4.0).unwrap();

        let food = db.get_food_by_id(recipe.food_id).unwrap();
        // default_serving_g = 400 / 4 = 100
        assert!((food.default_serving_g.unwrap() - 100.0).abs() < 0.01);
        // cal per 100g stays the same
        assert!((food.calories_per_100g - 165.0).abs() < 0.01);
    }

    #[test]
    fn test_recipe_remove_ingredient() {
        let db = Database::open_in_memory().unwrap();
        let chicken = db.insert_food(&sample_food()).unwrap();
        let rice = db.insert_food(&sample_ingredient_rice()).unwrap();
        let recipe = db.create_recipe("Mixed", 1.0).unwrap();
        db.add_recipe_ingredient(recipe.id, chicken.id, 100.0)
            .unwrap();
        db.add_recipe_ingredient(recipe.id, rice.id, 100.0).unwrap();

        assert!(
            db.remove_recipe_ingredient(recipe.id, "Brown Rice")
                .unwrap()
        );
        let detail = db.get_recipe_detail(recipe.id).unwrap();
        assert_eq!(detail.ingredients.len(), 1);
        assert!((detail.total_weight_g - 100.0).abs() < 0.01);
    }

    #[test]
    fn test_recipe_log_as_food() {
        let db = Database::open_in_memory().unwrap();
        let chicken = db.insert_food(&sample_food()).unwrap();
        let recipe = db.create_recipe("Meal Prep Chicken", 4.0).unwrap();
        db.add_recipe_ingredient(recipe.id, chicken.id, 800.0)
            .unwrap();

        // Log one portion as a meal
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        let food = db.get_food_by_id(recipe.food_id).unwrap();
        let serving = food.default_serving_g.unwrap(); // 800/4 = 200g
        assert!((serving - 200.0).abs() < 0.01);

        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date,
                meal_type: "dinner".to_string(),
                food_id: recipe.food_id,
                serving_g: serving,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        // 165 cal/100g * 200g / 100 = 330 kcal
        assert!((entry.calories.unwrap() - 330.0).abs() < 0.01);

        // Verify daily summary includes it
        let summary = db.build_daily_summary(date).unwrap();
        assert!((summary.total_calories - 330.0).abs() < 0.01);
    }

    #[test]
    fn test_delete_recipe() {
        let db = Database::open_in_memory().unwrap();
        let chicken = db.insert_food(&sample_food()).unwrap();
        let recipe = db.create_recipe("To Delete", 1.0).unwrap();
        db.add_recipe_ingredient(recipe.id, chicken.id, 100.0)
            .unwrap();
        let food_id = recipe.food_id;

        db.delete_recipe(recipe.id).unwrap();
        // Virtual food should be gone
        assert!(db.get_food_by_id(food_id).is_err());
        // Recipe should be gone
        assert!(db.get_recipe_by_id(recipe.id).is_err());
    }

    #[test]
    fn test_list_recipes() {
        let db = Database::open_in_memory().unwrap();
        assert!(db.list_recipes().unwrap().is_empty());

        db.create_recipe("Recipe A", 2.0).unwrap();
        db.create_recipe("Recipe B", 4.0).unwrap();
        let recipes = db.list_recipes().unwrap();
        assert_eq!(recipes.len(), 2);
    }

    // --- Export / Import tests ---

    #[test]
    fn test_export_all_empty() {
        let db = Database::open_in_memory().unwrap();
        let export = db.export_all().unwrap();
        assert_eq!(export.version, 3);
        assert!(export.device_id.is_some());
        assert!(export.foods.is_empty());
        assert!(export.meal_entries.is_empty());
        assert!(export.recipes.is_empty());
        assert!(export.recipe_ingredients.is_empty());
        assert!(export.targets.is_empty());
    }

    #[test]
    fn test_export_all_with_data() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        db.insert_meal_entry(&NewMealEntry {
            date,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();
        db.set_target(0, 2000, Some(30), Some(40), Some(30))
            .unwrap();

        let export = db.export_all().unwrap();
        assert_eq!(export.foods.len(), 1);
        assert_eq!(export.meal_entries.len(), 1);
        assert_eq!(export.targets.len(), 1);
        assert_eq!(export.targets[0].calories, 2000);
        assert_eq!(export.targets[0].day_of_week, 0);
    }

    #[test]
    fn test_import_into_empty_db() {
        let db = Database::open_in_memory().unwrap();

        // Create export data from another db
        let source_db = Database::open_in_memory().unwrap();
        let food = source_db.insert_food(&sample_food()).unwrap();
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        source_db
            .insert_meal_entry(&NewMealEntry {
                date,
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 200.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();
        source_db
            .set_target(0, 2000, Some(30), Some(40), Some(30))
            .unwrap();

        let export = source_db.export_all().unwrap();
        let summary = db.import_all(&export).unwrap();

        assert_eq!(summary.foods_imported, 1);
        assert_eq!(summary.meal_entries_imported, 1);
        assert_eq!(summary.targets_imported, 1);

        // Verify data was imported
        let imported_food = db.get_food_by_id(food.id).unwrap();
        assert_eq!(imported_food.name, "Chicken Breast");
        let target = db.get_target(0).unwrap().unwrap();
        assert_eq!(target.calories, 2000);
    }

    #[test]
    fn test_import_upsert_existing() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        // Create export with updated food name and bumped updated_at
        let export = db.export_all().unwrap();
        let mut modified = export;
        modified.foods[0].name = "Updated Chicken".to_string();
        modified.foods[0].updated_at = "2099-01-01T00:00:00+00:00".to_string();

        let summary = db.import_all(&modified).unwrap();
        assert_eq!(summary.foods_imported, 1);

        let updated_food = db.get_food_by_id(food.id).unwrap();
        assert_eq!(updated_food.name, "Updated Chicken");
    }

    #[test]
    fn test_get_recipe_by_food_name() {
        let db = Database::open_in_memory().unwrap();
        let recipe = db.create_recipe("My Stew", 3.0).unwrap();

        // Case-insensitive lookup
        let found = db.get_recipe_by_food_name("my stew").unwrap();
        assert_eq!(found.id, recipe.id);
        let found = db.get_recipe_by_food_name("MY STEW").unwrap();
        assert_eq!(found.id, recipe.id);

        // Not found
        assert!(db.get_recipe_by_food_name("nonexistent").is_err());
    }

    // --- v2 schema / sync tests ---

    #[test]
    fn test_insert_food_generates_uuid() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        assert!(!food.uuid.is_empty());
        assert!(!food.updated_at.is_empty());
        // UUID should be valid v4 format
        assert!(uuid::Uuid::parse_str(&food.uuid).is_ok());
    }

    #[test]
    fn test_insert_meal_generates_uuid() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 200.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();
        assert!(!entry.uuid.is_empty());
        assert!(!entry.updated_at.is_empty());
        assert!(uuid::Uuid::parse_str(&entry.uuid).is_ok());
    }

    #[test]
    fn test_update_meal_updates_timestamp() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();
        let original_updated = entry.updated_at.clone();

        // Small delay to ensure different timestamp
        std::thread::sleep(std::time::Duration::from_millis(10));

        let updated = db
            .update_meal_entry(
                entry.id,
                &UpdateMealEntry {
                    serving_g: Some(250.0),
                    meal_type: None,
                    date: None,
                    display_unit: None,
                    display_quantity: None,
                },
            )
            .unwrap();
        assert!(updated.updated_at >= original_updated);
        assert_eq!(updated.uuid, entry.uuid); // UUID should not change
    }

    #[test]
    fn test_merge_foods_new() {
        let db = Database::open_in_memory().unwrap();
        let incoming_uuid = Uuid::new_v4().to_string();
        let now = Local::now().to_rfc3339();

        let import_data = ExportData {
            version: 2,
            exported_at: now.clone(),
            device_id: Some("other-device".to_string()),
            foods: vec![Food {
                id: 999,
                uuid: incoming_uuid.clone(),
                name: "Remote Food".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 100.0,
                protein_per_100g: Some(10.0),
                carbs_per_100g: Some(20.0),
                fat_per_100g: Some(5.0),
                default_serving_g: None,
                source: "manual".to_string(),
                created_at: now.clone(),
                updated_at: now,
            }],
            meal_entries: vec![],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: None,
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.foods_imported, 1);

        // Should be findable by UUID
        let found = db.get_food_by_uuid(&incoming_uuid).unwrap().unwrap();
        assert_eq!(found.name, "Remote Food");
    }

    #[test]
    fn test_merge_foods_newer_wins() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        let import_data = ExportData {
            version: 2,
            exported_at: Local::now().to_rfc3339(),
            device_id: Some("other-device".to_string()),
            foods: vec![Food {
                id: 999,
                uuid: food.uuid.clone(),
                name: "Updated Name".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 200.0,
                protein_per_100g: Some(20.0),
                carbs_per_100g: Some(10.0),
                fat_per_100g: Some(5.0),
                default_serving_g: None,
                source: "manual".to_string(),
                created_at: food.created_at.clone(),
                updated_at: "2099-01-01T00:00:00+00:00".to_string(),
            }],
            meal_entries: vec![],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: None,
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.foods_imported, 1);

        let updated = db.get_food_by_id(food.id).unwrap();
        assert_eq!(updated.name, "Updated Name");
        assert_eq!(updated.calories_per_100g, 200.0);
    }

    #[test]
    fn test_merge_foods_older_skipped() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        let import_data = ExportData {
            version: 2,
            exported_at: Local::now().to_rfc3339(),
            device_id: Some("other-device".to_string()),
            foods: vec![Food {
                id: 999,
                uuid: food.uuid.clone(),
                name: "Should Not Update".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 200.0,
                protein_per_100g: None,
                carbs_per_100g: None,
                fat_per_100g: None,
                default_serving_g: None,
                source: "manual".to_string(),
                created_at: food.created_at.clone(),
                updated_at: "2000-01-01T00:00:00+00:00".to_string(),
            }],
            meal_entries: vec![],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: None,
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.foods_imported, 0);

        let unchanged = db.get_food_by_id(food.id).unwrap();
        assert_eq!(unchanged.name, "Chicken Breast");
    }

    #[test]
    fn test_merge_meal_entries() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry_uuid = Uuid::new_v4().to_string();

        let import_data = ExportData {
            version: 2,
            exported_at: Local::now().to_rfc3339(),
            device_id: Some("other-device".to_string()),
            foods: vec![food.clone()],
            meal_entries: vec![ExportMealEntry {
                id: 999,
                uuid: entry_uuid.clone(),
                date: "2024-06-15".to_string(),
                meal_type: "lunch".to_string(),
                food_id: 999,
                food_uuid: food.uuid.clone(),
                serving_g: 200.0,
                display_unit: None,
                display_quantity: None,
                created_at: Local::now().to_rfc3339(),
                updated_at: Local::now().to_rfc3339(),
            }],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: None,
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.meal_entries_imported, 1);

        // Verify the entry exists by checking entries for the date
        let entries = db
            .get_entries_for_date(NaiveDate::from_ymd_opt(2024, 6, 15).unwrap())
            .unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].uuid, entry_uuid);
        assert_eq!(entries[0].serving_g, 200.0);
    }

    #[test]
    fn test_merge_recipes() {
        let db = Database::open_in_memory().unwrap();
        let chicken = db.insert_food(&sample_food()).unwrap();

        // Create a virtual food for the recipe
        let recipe_food = db
            .insert_food(&NewFood {
                name: "Remote Recipe".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 150.0,
                protein_per_100g: Some(20.0),
                carbs_per_100g: Some(10.0),
                fat_per_100g: Some(5.0),
                default_serving_g: Some(200.0),
                source: "recipe".to_string(),
            })
            .unwrap();

        let recipe_uuid = Uuid::new_v4().to_string();
        let ing_uuid = Uuid::new_v4().to_string();
        let now = Local::now().to_rfc3339();

        let import_data = ExportData {
            version: 2,
            exported_at: now.clone(),
            device_id: Some("other-device".to_string()),
            foods: vec![chicken.clone(), recipe_food.clone()],
            meal_entries: vec![],
            recipes: vec![ExportRecipe {
                id: 999,
                uuid: recipe_uuid.clone(),
                food_id: 999,
                food_uuid: recipe_food.uuid.clone(),
                portions: 4.0,
                created_at: now.clone(),
                updated_at: now.clone(),
            }],
            recipe_ingredients: vec![ExportRecipeIngredient {
                id: 999,
                uuid: ing_uuid,
                recipe_id: 999,
                recipe_uuid: recipe_uuid.clone(),
                food_id: 999,
                food_uuid: chicken.uuid.clone(),
                quantity_g: 400.0,
            }],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: None,
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.recipes_imported, 1);
        assert_eq!(summary.recipe_ingredients_imported, 1);
    }

    #[test]
    fn test_merge_tombstones() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 200.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        let import_data = ExportData {
            version: 2,
            exported_at: Local::now().to_rfc3339(),
            device_id: Some("other-device".to_string()),
            foods: vec![],
            meal_entries: vec![],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: Some(vec![SyncTombstone {
                uuid: entry.uuid.clone(),
                table_name: "meal_entries".to_string(),
                deleted_at: "2099-01-01T00:00:00+00:00".to_string(),
            }]),
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.tombstones_processed, 1);

        // Entry should be deleted
        let entries = db
            .get_entries_for_date(NaiveDate::from_ymd_opt(2024, 6, 15).unwrap())
            .unwrap();
        assert!(entries.is_empty());

        // Tombstone should be stored locally
        let tombstones = db.get_tombstones().unwrap();
        assert_eq!(tombstones.len(), 1);
        assert_eq!(tombstones[0].uuid, entry.uuid);
    }

    #[test]
    fn test_merge_tombstone_older_than_record() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 200.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();

        // Tombstone has an old deleted_at — record should survive
        let import_data = ExportData {
            version: 2,
            exported_at: Local::now().to_rfc3339(),
            device_id: Some("other-device".to_string()),
            foods: vec![],
            meal_entries: vec![],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: Some(vec![SyncTombstone {
                uuid: entry.uuid.clone(),
                table_name: "meal_entries".to_string(),
                deleted_at: "2000-01-01T00:00:00+00:00".to_string(),
            }]),
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.tombstones_processed, 0);

        // Entry should still exist
        let entries = db
            .get_entries_for_date(NaiveDate::from_ymd_opt(2024, 6, 15).unwrap())
            .unwrap();
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_v1_import_still_works() {
        let db = Database::open_in_memory().unwrap();

        // Create a v1 export data (no UUIDs)
        let v1_data = ExportData {
            version: 1,
            exported_at: Local::now().to_rfc3339(),
            device_id: None,
            foods: vec![Food {
                id: 1,
                uuid: String::new(),
                name: "V1 Food".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 100.0,
                protein_per_100g: None,
                carbs_per_100g: None,
                fat_per_100g: None,
                default_serving_g: None,
                source: "manual".to_string(),
                created_at: Local::now().to_rfc3339(),
                updated_at: String::new(),
            }],
            meal_entries: vec![],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![],
            tombstones: None,
        };

        let summary = db.import_all(&v1_data).unwrap();
        assert_eq!(summary.foods_imported, 1);
        assert_eq!(summary.tombstones_processed, 0);

        let food = db.get_food_by_id(1).unwrap();
        assert_eq!(food.name, "V1 Food");
    }

    #[test]
    fn test_device_id_persistence() {
        let db = Database::open_in_memory().unwrap();
        let id1 = db.get_or_create_device_id().unwrap();
        let id2 = db.get_or_create_device_id().unwrap();
        assert_eq!(id1, id2);
        assert!(uuid::Uuid::parse_str(&id1).is_ok());
    }

    #[test]
    fn test_export_v2_format() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        db.insert_meal_entry(&NewMealEntry {
            date,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let export = db.export_all().unwrap();
        assert_eq!(export.version, 3);
        assert!(export.device_id.is_some());
        assert!(!export.foods[0].uuid.is_empty());
        assert!(!export.foods[0].updated_at.is_empty());
        assert!(!export.meal_entries[0].uuid.is_empty());
        assert!(!export.meal_entries[0].food_uuid.is_empty());
        assert_eq!(export.meal_entries[0].food_uuid, food.uuid);
        assert!(export.tombstones.is_some());
    }

    #[test]
    fn test_migration_v2_generates_uuids() {
        // Simulate a v1 database by creating one, then inserting data at v1 level
        // Since open_in_memory runs migrate() which goes all the way to v2,
        // we verify that data inserted after migration has UUIDs
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        assert!(!food.uuid.is_empty());

        let date = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        let entry = db
            .insert_meal_entry(&NewMealEntry {
                date,
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();
        assert!(!entry.uuid.is_empty());

        let recipe = db.create_recipe("Test Recipe", 2.0).unwrap();
        assert!(!recipe.uuid.is_empty());
    }

    #[test]
    fn test_tombstone_crud() {
        let db = Database::open_in_memory().unwrap();

        // Initially empty
        assert!(db.get_tombstones().unwrap().is_empty());

        // Record tombstones
        db.record_tombstone("uuid-1", "foods").unwrap();
        db.record_tombstone("uuid-2", "meal_entries").unwrap();

        let tombstones = db.get_tombstones().unwrap();
        assert_eq!(tombstones.len(), 2);

        // Clear
        db.clear_tombstones().unwrap();
        assert!(db.get_tombstones().unwrap().is_empty());
    }

    // --- Delta sync tests ---

    #[test]
    fn test_get_foods_since() {
        let db = Database::open_in_memory().unwrap();

        // Insert two foods
        let food1 = db.insert_food(&sample_food()).unwrap();
        let food2 = db
            .insert_food(&NewFood {
                name: "Brown Rice".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 112.0,
                protein_per_100g: Some(2.6),
                carbs_per_100g: Some(23.5),
                fat_per_100g: Some(0.9),
                default_serving_g: None,
                source: "manual".to_string(),
            })
            .unwrap();

        // All foods since epoch should return both
        let all = db.get_foods_since("1970-01-01T00:00:00+00:00").unwrap();
        assert_eq!(all.len(), 2);

        // Foods since a future time should return none
        let none = db.get_foods_since("2099-01-01T00:00:00+00:00").unwrap();
        assert!(none.is_empty());

        // get_all_foods should return both
        let all_foods = db.get_all_foods().unwrap();
        assert_eq!(all_foods.len(), 2);
        assert_eq!(all_foods[0].id, food1.id);
        assert_eq!(all_foods[1].id, food2.id);
    }

    #[test]
    fn test_get_meal_entries_since() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        // All entries since epoch
        let all = db
            .get_meal_entries_since("1970-01-01T00:00:00+00:00")
            .unwrap();
        assert_eq!(all.len(), 1);
        assert!(!all[0].food_uuid.is_empty());

        // None since future
        let none = db
            .get_meal_entries_since("2099-01-01T00:00:00+00:00")
            .unwrap();
        assert!(none.is_empty());

        // get_all_meal_entries_export
        let all_export = db.get_all_meal_entries_export().unwrap();
        assert_eq!(all_export.len(), 1);
    }

    #[test]
    fn test_get_tombstones_since() {
        let db = Database::open_in_memory().unwrap();

        db.record_tombstone("uuid-1", "foods").unwrap();
        db.record_tombstone("uuid-2", "meal_entries").unwrap();

        let all = db
            .get_tombstones_since("1970-01-01T00:00:00+00:00")
            .unwrap();
        assert_eq!(all.len(), 2);

        let none = db
            .get_tombstones_since("2099-01-01T00:00:00+00:00")
            .unwrap();
        assert!(none.is_empty());
    }

    #[test]
    fn test_changes_since_full() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();
        db.record_tombstone("dead-uuid", "foods").unwrap();

        // Full sync (no since param)
        let payload = db.changes_since(None, "2024-06-15T12:00:00Z").unwrap();
        assert_eq!(payload.foods.len(), 1);
        assert_eq!(payload.meal_entries.len(), 1);
        assert_eq!(payload.tombstones.len(), 1);
        assert_eq!(payload.server_timestamp, "2024-06-15T12:00:00Z");
    }

    #[test]
    fn test_changes_since_incremental() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        // Record a timestamp after food creation
        let mid_timestamp = "2099-01-01T00:00:00+00:00";

        // Delta since future returns nothing
        let payload = db.changes_since(Some(mid_timestamp), "now").unwrap();
        assert!(payload.foods.is_empty());
        assert!(payload.meal_entries.is_empty());
        assert!(payload.tombstones.is_empty());

        // Delta since epoch returns everything
        let payload = db
            .changes_since(Some("1970-01-01T00:00:00+00:00"), "now")
            .unwrap();
        assert_eq!(payload.foods.len(), 1);
        assert_eq!(payload.foods[0].id, food.id);
    }

    #[test]
    fn test_changes_since_includes_all_entity_types() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        // Create recipe
        let recipe = db.create_recipe("Test Recipe", 4.0).unwrap();
        db.add_recipe_ingredient(recipe.id, food.id, 200.0).unwrap();

        // Set target
        db.set_target(0, 2000, Some(40), Some(30), Some(30))
            .unwrap();

        // Log weight
        db.upsert_weight(&NewWeightEntry {
            date: NaiveDate::from_ymd_opt(2025, 1, 15).unwrap(),
            weight_kg: 80.0,
            source: "manual".to_string(),
            notes: None,
        })
        .unwrap();

        let payload = db.changes_since(None, "now").unwrap();
        // foods: sample_food + recipe virtual food = 2
        assert_eq!(payload.foods.len(), 2);
        assert_eq!(payload.recipes.len(), 1);
        assert_eq!(payload.recipe_ingredients.len(), 1);
        assert_eq!(payload.targets.len(), 1);
        assert_eq!(payload.weight_entries.len(), 1);
    }

    #[test]
    fn test_changes_since_incremental_new_entity_types() {
        let db = Database::open_in_memory().unwrap();
        db.insert_food(&sample_food()).unwrap();

        // Create recipe (gets a timestamp)
        db.create_recipe("Test Recipe", 4.0).unwrap();

        // Set target
        db.set_target(0, 2000, Some(40), Some(30), Some(30))
            .unwrap();

        // Far future — nothing returned
        let payload = db
            .changes_since(Some("2099-01-01T00:00:00+00:00"), "now")
            .unwrap();
        assert!(payload.recipes.is_empty());
        assert!(payload.targets.is_empty());
        assert!(payload.weight_entries.is_empty());
        assert!(payload.recipe_ingredients.is_empty());

        // Epoch — everything returned
        let payload = db
            .changes_since(Some("1970-01-01T00:00:00+00:00"), "now")
            .unwrap();
        assert_eq!(payload.foods.len(), 2); // sample_food + recipe virtual food
        assert_eq!(payload.recipes.len(), 1);
        assert_eq!(payload.targets.len(), 1);
    }

    #[test]
    fn test_apply_remote_changes_new_food() {
        let db = Database::open_in_memory().unwrap();

        let incoming_food = Food {
            id: 0,
            uuid: "remote-uuid-1".to_string(),
            name: "Remote Food".to_string(),
            brand: Some("Remote Brand".to_string()),
            barcode: None,
            calories_per_100g: 200.0,
            protein_per_100g: Some(20.0),
            carbs_per_100g: Some(10.0),
            fat_per_100g: Some(5.0),
            default_serving_g: Some(100.0),
            source: "openfoodfacts".to_string(),
            created_at: "2024-01-01T00:00:00+00:00".to_string(),
            updated_at: "2024-06-01T00:00:00+00:00".to_string(),
        };

        db.apply_remote_changes(&[incoming_food], &[], &[], &[], &[], &[], &[])
            .unwrap();

        let food = db.get_food_by_uuid("remote-uuid-1").unwrap().unwrap();
        assert_eq!(food.name, "Remote Food");
    }

    #[test]
    fn test_apply_remote_changes_lww_food() {
        let db = Database::open_in_memory().unwrap();
        let local = db.insert_food(&sample_food()).unwrap();

        let incoming = Food {
            id: 0,
            uuid: local.uuid.clone(),
            name: "Updated Name".to_string(),
            brand: Some("New Brand".to_string()),
            barcode: local.barcode.clone(),
            calories_per_100g: 999.0,
            protein_per_100g: Some(99.0),
            carbs_per_100g: Some(0.0),
            fat_per_100g: Some(0.0),
            default_serving_g: Some(100.0),
            source: "manual".to_string(),
            created_at: local.created_at.clone(),
            updated_at: "2099-01-01T00:00:00+00:00".to_string(),
        };

        db.apply_remote_changes(&[incoming], &[], &[], &[], &[], &[], &[])
            .unwrap();

        let updated = db.get_food_by_uuid(&local.uuid).unwrap().unwrap();
        assert_eq!(updated.name, "Updated Name");
        assert_eq!(updated.calories_per_100g, 999.0);
    }

    #[test]
    fn test_apply_remote_changes_lww_food_older_ignored() {
        let db = Database::open_in_memory().unwrap();
        let local = db.insert_food(&sample_food()).unwrap();

        let incoming = Food {
            id: 0,
            uuid: local.uuid.clone(),
            name: "Old Name".to_string(),
            brand: None,
            barcode: None,
            calories_per_100g: 1.0,
            protein_per_100g: None,
            carbs_per_100g: None,
            fat_per_100g: None,
            default_serving_g: None,
            source: "manual".to_string(),
            created_at: "2000-01-01T00:00:00+00:00".to_string(),
            updated_at: "2000-01-01T00:00:00+00:00".to_string(),
        };

        db.apply_remote_changes(&[incoming], &[], &[], &[], &[], &[], &[])
            .unwrap();

        let unchanged = db.get_food_by_uuid(&local.uuid).unwrap().unwrap();
        assert_eq!(unchanged.name, "Chicken Breast");
    }

    #[test]
    fn test_apply_remote_changes_meal_entry() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        let incoming_entry = crate::models::ExportMealEntry {
            id: 0,
            uuid: "remote-meal-uuid-1".to_string(),
            date: "2024-06-15".to_string(),
            meal_type: "lunch".to_string(),
            food_id: 0,
            food_uuid: food.uuid.clone(),
            serving_g: 250.0,
            display_unit: None,
            display_quantity: None,
            created_at: "2024-06-15T12:00:00+00:00".to_string(),
            updated_at: "2024-06-15T12:00:00+00:00".to_string(),
        };

        db.apply_remote_changes(&[], &[incoming_entry], &[], &[], &[], &[], &[])
            .unwrap();

        let entries = db.get_all_meal_entries_export().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].uuid, "remote-meal-uuid-1");
        assert_eq!(entries[0].serving_g, 250.0);
    }

    #[test]
    fn test_apply_remote_changes_tombstone() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        let tombstone = SyncTombstone {
            uuid: food.uuid.clone(),
            table_name: "foods".to_string(),
            deleted_at: "2099-01-01T00:00:00+00:00".to_string(),
        };

        db.apply_remote_changes(&[], &[], &[], &[], &[], &[], &[tombstone])
            .unwrap();

        assert!(db.get_food_by_uuid(&food.uuid).unwrap().is_none());

        let stored = db.get_tombstones().unwrap();
        assert_eq!(stored.len(), 1);
        assert_eq!(stored[0].uuid, food.uuid);
    }

    #[test]
    fn test_apply_remote_changes_recipes() {
        let db = Database::open_in_memory().unwrap();

        // Create a virtual food for the recipe
        let recipe_food = db
            .insert_food(&NewFood {
                name: "Remote Recipe".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 150.0,
                protein_per_100g: Some(20.0),
                carbs_per_100g: Some(10.0),
                fat_per_100g: Some(5.0),
                default_serving_g: Some(200.0),
                source: "recipe".to_string(),
            })
            .unwrap();
        let ingredient_food = db.insert_food(&sample_food()).unwrap();

        let recipe_uuid = Uuid::new_v4().to_string();
        let ing_uuid = Uuid::new_v4().to_string();
        let now = Local::now().to_rfc3339();

        let recipes = vec![ExportRecipe {
            id: 0,
            uuid: recipe_uuid.clone(),
            food_id: 0,
            food_uuid: recipe_food.uuid.clone(),
            portions: 4.0,
            created_at: now.clone(),
            updated_at: now.clone(),
        }];

        let recipe_ingredients = vec![ExportRecipeIngredient {
            id: 0,
            uuid: ing_uuid,
            recipe_id: 0,
            recipe_uuid: recipe_uuid.clone(),
            food_id: 0,
            food_uuid: ingredient_food.uuid.clone(),
            quantity_g: 400.0,
        }];

        db.apply_remote_changes(&[], &[], &recipes, &recipe_ingredients, &[], &[], &[])
            .unwrap();

        // Recipe should exist
        let imported_recipe = db.get_recipe_by_uuid(&recipe_uuid).unwrap().unwrap();
        assert!((imported_recipe.portions - 4.0).abs() < f64::EPSILON);

        // Ingredient should exist
        let ingredients = db.get_recipe_ingredients(imported_recipe.id).unwrap();
        assert_eq!(ingredients.len(), 1);
        assert!((ingredients[0].quantity_g - 400.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_apply_remote_changes_targets_lww() {
        let db = Database::open_in_memory().unwrap();

        // Set a local target
        db.set_target(0, 1800, Some(40), Some(30), Some(30))
            .unwrap();

        // Apply a newer remote target
        let targets = vec![ExportTarget {
            day_of_week: 0,
            calories: 2200,
            protein_pct: Some(35),
            carbs_pct: Some(40),
            fat_pct: Some(25),
            updated_at: Some("2099-01-01T00:00:00+00:00".to_string()),
        }];

        db.apply_remote_changes(&[], &[], &[], &[], &targets, &[], &[])
            .unwrap();

        let target = db.get_target(0).unwrap().unwrap();
        assert_eq!(target.calories, 2200);
        assert_eq!(target.protein_pct, Some(35));
    }

    #[test]
    fn test_apply_remote_changes_targets_older_ignored() {
        let db = Database::open_in_memory().unwrap();

        // Set a local target (gets current timestamp)
        db.set_target(0, 1800, Some(40), Some(30), Some(30))
            .unwrap();

        // Apply an older remote target
        let targets = vec![ExportTarget {
            day_of_week: 0,
            calories: 1200,
            protein_pct: None,
            carbs_pct: None,
            fat_pct: None,
            updated_at: Some("2000-01-01T00:00:00+00:00".to_string()),
        }];

        db.apply_remote_changes(&[], &[], &[], &[], &targets, &[], &[])
            .unwrap();

        let target = db.get_target(0).unwrap().unwrap();
        assert_eq!(target.calories, 1800); // unchanged
    }

    #[test]
    fn test_apply_remote_changes_weight_entries_lww() {
        let db = Database::open_in_memory().unwrap();

        // Insert a local weight
        db.upsert_weight(&NewWeightEntry {
            date: NaiveDate::from_ymd_opt(2025, 1, 15).unwrap(),
            weight_kg: 80.0,
            source: "manual".to_string(),
            notes: None,
        })
        .unwrap();

        // Apply a newer remote weight for the same date
        let weights = vec![ExportWeightEntry {
            uuid: Uuid::new_v4().to_string(),
            date: "2025-01-15".to_string(),
            weight_kg: 79.5,
            source: "scale".to_string(),
            notes: Some("Smart scale reading".to_string()),
            created_at: "2025-01-15T08:00:00+00:00".to_string(),
            updated_at: "2099-01-01T00:00:00+00:00".to_string(),
        }];

        db.apply_remote_changes(&[], &[], &[], &[], &[], &weights, &[])
            .unwrap();

        let entry = db
            .get_weight(NaiveDate::from_ymd_opt(2025, 1, 15).unwrap())
            .unwrap()
            .unwrap();
        assert!((entry.weight_kg - 79.5).abs() < f64::EPSILON);
        assert_eq!(entry.source, "scale");
    }

    #[test]
    fn test_apply_remote_changes_weight_entries_older_ignored() {
        let db = Database::open_in_memory().unwrap();

        // Insert a local weight (gets current timestamp)
        db.upsert_weight(&NewWeightEntry {
            date: NaiveDate::from_ymd_opt(2025, 1, 15).unwrap(),
            weight_kg: 80.0,
            source: "manual".to_string(),
            notes: None,
        })
        .unwrap();

        // Apply an older remote weight for the same date
        let weights = vec![ExportWeightEntry {
            uuid: Uuid::new_v4().to_string(),
            date: "2025-01-15".to_string(),
            weight_kg: 75.0,
            source: "old_scale".to_string(),
            notes: None,
            created_at: "2020-01-01T00:00:00+00:00".to_string(),
            updated_at: "2020-01-01T00:00:00+00:00".to_string(),
        }];

        db.apply_remote_changes(&[], &[], &[], &[], &[], &weights, &[])
            .unwrap();

        let entry = db
            .get_weight(NaiveDate::from_ymd_opt(2025, 1, 15).unwrap())
            .unwrap()
            .unwrap();
        assert!((entry.weight_kg - 80.0).abs() < f64::EPSILON); // unchanged
    }

    #[test]
    fn test_apply_remote_changes_recipe_tombstone() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let recipe = db.create_recipe("To Delete", 2.0).unwrap();
        db.add_recipe_ingredient(recipe.id, food.id, 100.0).unwrap();

        let tombstone = SyncTombstone {
            uuid: recipe.uuid.clone(),
            table_name: "recipes".to_string(),
            deleted_at: "2099-01-01T00:00:00+00:00".to_string(),
        };

        db.apply_remote_changes(&[], &[], &[], &[], &[], &[], &[tombstone])
            .unwrap();

        assert!(db.get_recipe_by_uuid(&recipe.uuid).unwrap().is_none());
    }

    // --- Weight entry tests ---

    fn sample_weight_entry(date: NaiveDate) -> NewWeightEntry {
        NewWeightEntry {
            date,
            weight_kg: 80.5,
            source: "manual".to_string(),
            notes: Some("Morning weigh-in".to_string()),
        }
    }

    #[test]
    fn test_upsert_weight_creates_new_entry() {
        let db = Database::open_in_memory().unwrap();
        let date = NaiveDate::from_ymd_opt(2025, 1, 15).unwrap();
        let entry = db.upsert_weight(&sample_weight_entry(date)).unwrap();

        assert_eq!(entry.date, date);
        assert!((entry.weight_kg - 80.5).abs() < f64::EPSILON);
        assert_eq!(entry.source, "manual");
        assert_eq!(entry.notes.as_deref(), Some("Morning weigh-in"));
        assert!(!entry.uuid.is_empty());
    }

    #[test]
    fn test_upsert_weight_replaces_existing_for_same_date() {
        let db = Database::open_in_memory().unwrap();
        let date = NaiveDate::from_ymd_opt(2025, 1, 15).unwrap();

        let first = db.upsert_weight(&sample_weight_entry(date)).unwrap();
        assert!((first.weight_kg - 80.5).abs() < f64::EPSILON);

        let updated = db
            .upsert_weight(&NewWeightEntry {
                date,
                weight_kg: 79.8,
                source: "manual".to_string(),
                notes: Some("Evening weigh-in".to_string()),
            })
            .unwrap();

        assert!((updated.weight_kg - 79.8).abs() < f64::EPSILON);
        assert_eq!(updated.notes.as_deref(), Some("Evening weigh-in"));

        // Should only be one entry for this date
        let history = db.get_weight_history(None).unwrap();
        assert_eq!(history.len(), 1);
    }

    #[test]
    fn test_get_weight_returns_none_for_missing_date() {
        let db = Database::open_in_memory().unwrap();
        let date = NaiveDate::from_ymd_opt(2025, 6, 1).unwrap();
        let result = db.get_weight(date).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_get_weight_returns_entry_for_existing_date() {
        let db = Database::open_in_memory().unwrap();
        let date = NaiveDate::from_ymd_opt(2025, 1, 15).unwrap();
        db.upsert_weight(&sample_weight_entry(date)).unwrap();

        let result = db.get_weight(date).unwrap();
        assert!(result.is_some());
        let entry = result.unwrap();
        assert_eq!(entry.date, date);
        assert!((entry.weight_kg - 80.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_get_weight_history_ordered_by_date_desc() {
        let db = Database::open_in_memory().unwrap();
        let dates = [
            NaiveDate::from_ymd_opt(2025, 1, 10).unwrap(),
            NaiveDate::from_ymd_opt(2025, 1, 12).unwrap(),
            NaiveDate::from_ymd_opt(2025, 1, 11).unwrap(),
        ];
        for date in &dates {
            db.upsert_weight(&sample_weight_entry(*date)).unwrap();
        }

        let history = db.get_weight_history(None).unwrap();
        assert_eq!(history.len(), 3);
        assert_eq!(history[0].date, dates[1]); // 2025-01-12 (most recent)
        assert_eq!(history[1].date, dates[2]); // 2025-01-11
        assert_eq!(history[2].date, dates[0]); // 2025-01-10
    }

    #[test]
    fn test_get_weight_history_with_days_limit() {
        let db = Database::open_in_memory().unwrap();
        for day in 1..=5 {
            let date = NaiveDate::from_ymd_opt(2025, 1, day).unwrap();
            db.upsert_weight(&sample_weight_entry(date)).unwrap();
        }

        let history = db.get_weight_history(Some(3)).unwrap();
        assert_eq!(history.len(), 3);
        // Most recent first
        assert_eq!(
            history[0].date,
            NaiveDate::from_ymd_opt(2025, 1, 5).unwrap()
        );
    }

    #[test]
    fn test_delete_weight() {
        let db = Database::open_in_memory().unwrap();
        let date = NaiveDate::from_ymd_opt(2025, 1, 15).unwrap();
        let entry = db.upsert_weight(&sample_weight_entry(date)).unwrap();

        db.delete_weight(entry.id).unwrap();
        let result = db.get_weight(date).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_delete_weight_not_found() {
        let db = Database::open_in_memory().unwrap();
        let result = db.delete_weight(9999);
        assert!(result.is_err());
    }

    #[test]
    fn test_export_import_roundtrip_includes_weight_entries() {
        let db = Database::open_in_memory().unwrap();

        // Add some weight entries
        for day in 1..=3 {
            let date = NaiveDate::from_ymd_opt(2025, 1, day).unwrap();
            db.upsert_weight(&NewWeightEntry {
                date,
                weight_kg: 80.0 + f64::from(day),
                source: "manual".to_string(),
                notes: None,
            })
            .unwrap();
        }

        let exported = db.export_all().unwrap();
        assert_eq!(exported.weight_entries.len(), 3);

        // Import into a fresh DB
        let db2 = Database::open_in_memory().unwrap();
        let summary = db2.import_all(&exported).unwrap();
        assert_eq!(summary.weight_entries_imported, 3);

        let history = db2.get_weight_history(None).unwrap();
        assert_eq!(history.len(), 3);
    }

    #[test]
    fn test_merge_import_weight_lww() {
        let db = Database::open_in_memory().unwrap();

        // Create an initial weight entry
        let date = NaiveDate::from_ymd_opt(2025, 1, 15).unwrap();
        let entry = db.upsert_weight(&sample_weight_entry(date)).unwrap();

        // Import data with a newer updated_at for the same date
        let import_data = ExportData {
            version: 2,
            exported_at: "2025-01-16T00:00:00Z".to_string(),
            device_id: None,
            foods: vec![],
            meal_entries: vec![],
            recipes: vec![],
            recipe_ingredients: vec![],
            target: None,
            targets: vec![],
            weight_entries: vec![crate::models::ExportWeightEntry {
                uuid: "new-uuid".to_string(),
                date: "2025-01-15".to_string(),
                weight_kg: 79.0,
                source: "apple_health".to_string(),
                notes: Some("From Apple Health".to_string()),
                created_at: entry.created_at.clone(),
                updated_at: "2099-01-01T00:00:00Z".to_string(),
            }],
            tombstones: None,
        };

        let summary = db.import_all(&import_data).unwrap();
        assert_eq!(summary.weight_entries_imported, 1);

        let updated = db.get_weight(date).unwrap().unwrap();
        assert!((updated.weight_kg - 79.0).abs() < f64::EPSILON);
        assert_eq!(updated.source, "apple_health");
    }

    #[test]
    fn test_migration_creates_weight_entries_table() {
        let db = Database::open_in_memory().unwrap();
        // If migration ran successfully, we should be able to query the table
        let count: i64 = db
            .conn
            .query_row("SELECT COUNT(*) FROM weight_entries", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);
    }

    // --- Recently logged foods tests ---

    #[test]
    fn test_recently_logged_foods_empty() {
        let db = Database::open_in_memory().unwrap();
        let result = db.get_recently_logged_foods(10).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_recently_logged_foods_single_entry() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let result = db.get_recently_logged_foods(10).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].food.id, food.id);
        assert!((result[0].last_serving_g - 200.0).abs() < f64::EPSILON);
        assert_eq!(result[0].last_meal_type, "lunch");
        assert_eq!(result[0].log_count, 1);
        assert_eq!(result[0].last_logged, "2024-06-15");
    }

    #[test]
    fn test_recently_logged_foods_ordering_and_dedup() {
        let db = Database::open_in_memory().unwrap();
        let chicken = db.insert_food(&sample_food()).unwrap();
        let rice = db
            .insert_food(&NewFood {
                name: "Brown Rice".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 112.0,
                protein_per_100g: Some(2.6),
                carbs_per_100g: Some(23.5),
                fat_per_100g: Some(0.9),
                default_serving_g: None,
                source: "manual".to_string(),
            })
            .unwrap();

        // Log chicken 3 times on different dates
        for day in [10, 12, 14] {
            db.insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, day).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: chicken.id,
                serving_g: 150.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();
        }

        // Log rice once on a more recent date
        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 16).unwrap(),
            meal_type: "dinner".to_string(),
            food_id: rice.id,
            serving_g: 250.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let result = db.get_recently_logged_foods(10).unwrap();
        assert_eq!(result.len(), 2);
        // Rice is more recent (June 16 vs June 14)
        assert_eq!(result[0].food.name, "Brown Rice");
        assert_eq!(result[0].log_count, 1);
        // Chicken is second
        assert_eq!(result[1].food.name, "Chicken Breast");
        assert_eq!(result[1].log_count, 3);
    }

    #[test]
    fn test_recently_logged_foods_limit() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let rice = db
            .insert_food(&NewFood {
                name: "Brown Rice".to_string(),
                brand: None,
                barcode: None,
                calories_per_100g: 112.0,
                protein_per_100g: Some(2.6),
                carbs_per_100g: Some(23.5),
                fat_per_100g: Some(0.9),
                default_serving_g: None,
                source: "manual".to_string(),
            })
            .unwrap();

        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();
        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
            meal_type: "dinner".to_string(),
            food_id: rice.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let result = db.get_recently_logged_foods(1).unwrap();
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_recently_logged_foods_uses_most_recent_entry() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();

        // First entry: 100g breakfast
        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 10).unwrap(),
            meal_type: "breakfast".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        // Second (more recent) entry: 250g dinner
        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
            meal_type: "dinner".to_string(),
            food_id: food.id,
            serving_g: 250.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let result = db.get_recently_logged_foods(10).unwrap();
        assert_eq!(result.len(), 1);
        // Should use the most recent entry's serving/meal
        assert!((result[0].last_serving_g - 250.0).abs() < f64::EPSILON);
        assert_eq!(result[0].last_meal_type, "dinner");
        assert_eq!(result[0].last_logged, "2024-06-15");
        assert_eq!(result[0].log_count, 2);
    }

    // --- Logging streak tests ---

    #[test]
    fn test_logging_streak_zero_days() {
        let db = Database::open_in_memory().unwrap();
        let today = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        assert_eq!(db.get_logging_streak(today).unwrap(), 0);
    }

    #[test]
    fn test_logging_streak_one_day_today() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        db.insert_meal_entry(&NewMealEntry {
            date: today,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        assert_eq!(db.get_logging_streak(today).unwrap(), 1);
    }

    #[test]
    fn test_logging_streak_starts_from_yesterday() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();
        let yesterday = NaiveDate::from_ymd_opt(2024, 6, 14).unwrap();

        // No entry today, but yesterday has one
        db.insert_meal_entry(&NewMealEntry {
            date: yesterday,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        assert_eq!(db.get_logging_streak(today).unwrap(), 1);
    }

    #[test]
    fn test_logging_streak_multiple_consecutive_days() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        // Log meals for 5 consecutive days ending today
        for day in 11..=15 {
            db.insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, day).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();
        }

        assert_eq!(db.get_logging_streak(today).unwrap(), 5);
    }

    #[test]
    fn test_logging_streak_gap_in_middle() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        // Log today, yesterday, skip a day, then another
        for day in [15, 14, 12] {
            db.insert_meal_entry(&NewMealEntry {
                date: NaiveDate::from_ymd_opt(2024, 6, day).unwrap(),
                meal_type: "lunch".to_string(),
                food_id: food.id,
                serving_g: 100.0,
                display_unit: None,
                display_quantity: None,
            })
            .unwrap();
        }

        // Streak should be 2 (today + yesterday), gap on June 13
        assert_eq!(db.get_logging_streak(today).unwrap(), 2);
    }

    #[test]
    fn test_logging_streak_no_recent_entries() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = NaiveDate::from_ymd_opt(2024, 6, 15).unwrap();

        // Old entry, not today or yesterday
        db.insert_meal_entry(&NewMealEntry {
            date: NaiveDate::from_ymd_opt(2024, 6, 10).unwrap(),
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        assert_eq!(db.get_logging_streak(today).unwrap(), 0);
    }

    // --- Calorie average tests ---

    #[test]
    fn test_calorie_average_no_entries() {
        let db = Database::open_in_memory().unwrap();
        let avg = db.get_calorie_average(7).unwrap();
        assert!((avg - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_calorie_average_single_day() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = Local::now().date_naive();

        // 200g of chicken: 165 * 200 / 100 = 330 kcal
        db.insert_meal_entry(&NewMealEntry {
            date: today,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        let avg = db.get_calorie_average(7).unwrap();
        assert!((avg - 330.0).abs() < 0.01);
    }

    #[test]
    fn test_calorie_average_multiple_days() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = Local::now().date_naive();

        // Day 1 (today): 200g = 330 kcal
        db.insert_meal_entry(&NewMealEntry {
            date: today,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        // Day 2 (yesterday): 100g = 165 kcal
        let yesterday = today - chrono::Duration::days(1);
        db.insert_meal_entry(&NewMealEntry {
            date: yesterday,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 100.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        // Average of 330 and 165 = 247.5
        let avg = db.get_calorie_average(7).unwrap();
        assert!((avg - 247.5).abs() < 0.01);
    }

    #[test]
    fn test_calorie_average_skips_zero_days() {
        let db = Database::open_in_memory().unwrap();
        let food = db.insert_food(&sample_food()).unwrap();
        let today = Local::now().date_naive();

        // Only log on today: 200g = 330 kcal
        db.insert_meal_entry(&NewMealEntry {
            date: today,
            meal_type: "lunch".to_string(),
            food_id: food.id,
            serving_g: 200.0,
            display_unit: None,
            display_quantity: None,
        })
        .unwrap();

        // Averaging over 7 days but only 1 day has entries
        // Should return 330 (not 330/7)
        let avg = db.get_calorie_average(7).unwrap();
        assert!((avg - 330.0).abs() < 0.01);
    }

    // --- User settings / goal weight tests ---

    #[test]
    fn test_user_settings_set_get() {
        let db = Database::open_in_memory().unwrap();
        db.set_setting("test_key", "test_value").unwrap();
        let val = db.get_setting("test_key").unwrap();
        assert_eq!(val.as_deref(), Some("test_value"));
    }

    #[test]
    fn test_user_settings_get_nonexistent() {
        let db = Database::open_in_memory().unwrap();
        let val = db.get_setting("nonexistent").unwrap();
        assert!(val.is_none());
    }

    #[test]
    fn test_user_settings_upsert() {
        let db = Database::open_in_memory().unwrap();
        db.set_setting("key", "value1").unwrap();
        db.set_setting("key", "value2").unwrap();
        let val = db.get_setting("key").unwrap();
        assert_eq!(val.as_deref(), Some("value2"));
    }

    #[test]
    fn test_user_settings_delete() {
        let db = Database::open_in_memory().unwrap();
        db.set_setting("key", "value").unwrap();
        assert!(db.delete_setting("key").unwrap());
        assert!(db.get_setting("key").unwrap().is_none());
        // Deleting again returns false
        assert!(!db.delete_setting("key").unwrap());
    }

    #[test]
    fn test_migration_creates_user_settings_table() {
        let db = Database::open_in_memory().unwrap();
        let count: i64 = db
            .conn
            .query_row("SELECT COUNT(*) FROM user_settings", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);
    }
}