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d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1fdb9
 
 
 
 
 
 
 
 
 
 
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
import { Pool } from 'pg';

function mapBet(row) {
  if (!row) {
    return null;
  }

  return {
    id: Number(row.id),
    discordUserId: row.discord_user_id,
    betNumber: Number(row.bet_number),
    book: row.book,
    sport: row.sport,
    oddsInput: row.odds_input,
    normalizedDecimalOdds: Number(row.normalized_decimal_odds),
    prop: row.prop,
    stake: Number(row.stake),
    unitsValue: row.units_value === null ? null : Number(row.units_value),
    status: row.status,
    profitLoss: row.profit_loss === null ? null : Number(row.profit_loss),
    rawInput: row.raw_input,
    createdAt: row.created_at,
    resolvedAt: row.resolved_at,
    deletedAt: row.deleted_at,
    deletedReason: row.deleted_reason,
  };
}

function numberOrNull(value) {
  return value === null || value === undefined ? null : Number(value);
}

function buildWhereClause(filters = {}, options = {}) {
  const clauses = [];
  const values = [];
  let index = 1;

  clauses.push(`discord_user_id = $${index++}`);
  values.push(filters.userId);

  if (!options.includeDeleted) {
    clauses.push('deleted_at IS NULL');
  }

  if (filters.book) {
    clauses.push(`book = $${index++}`);
    values.push(filters.book);
  }

  if (filters.sport) {
    clauses.push(`sport = $${index++}`);
    values.push(filters.sport);
  }

  if (filters.status) {
    if (filters.status === 'deleted') {
      clauses.push('deleted_at IS NOT NULL');
    } else {
      clauses.push(`status = $${index++}`);
      values.push(filters.status);
    }
  }

  if (filters.dateWindow && filters.dateWindow !== 'all') {
    if (filters.dateWindow === 'today') {
      clauses.push('created_at >= DATE_TRUNC(\'day\', NOW())');
    } else if (filters.dateWindow === '7d') {
      clauses.push('created_at >= NOW() - INTERVAL \'7 days\'');
    } else if (filters.dateWindow === '30d') {
      clauses.push('created_at >= NOW() - INTERVAL \'30 days\'');
    }
  }

  return {
    clause: clauses.join(' AND '),
    values,
  };
}

function computeAnalytics(rows, profile) {
  const activeRows = rows.filter((row) => row.deletedAt === null);
  const wins = activeRows.filter((row) => row.status === 'win').length;
  const losses = activeRows.filter((row) => row.status === 'loss').length;
  const voids = activeRows.filter((row) => row.status === 'void').length;
  const openBets = activeRows.filter((row) => row.status === 'open').length;
  const settledRows = activeRows.filter((row) => row.status !== 'open');
  const gradedRows = activeRows.filter((row) => row.status === 'win' || row.status === 'loss');
  const settledStake = gradedRows.reduce((total, row) => total + row.stake, 0);
  const netProfit = settledRows.reduce((total, row) => total + (row.profitLoss ?? 0), 0);
  const totalUnits = settledRows.reduce(
    (total, row) => total + (row.unitsValue ?? deriveUnitsValue(row.stake, profile.unitSize)),
    0
  );
  const bankrollNow = profile.startingBankroll !== null ? profile.startingBankroll + netProfit : null;

  return {
    totalBets: activeRows.length,
    openBets,
    wins,
    losses,
    voids,
    settledStake,
    netProfit,
    roiPercent: settledStake > 0 ? (netProfit / settledStake) * 100 : 0,
    totalUnits,
    unitSize: profile.unitSize,
    startingBankroll: profile.startingBankroll,
    bankrollNow,
    winRatePercent: gradedRows.length > 0 ? (wins / gradedRows.length) * 100 : 0,
  };
}

function deriveUnitsValue(stake, unitSize) {
  if (!unitSize || unitSize <= 0) {
    return 0;
  }

  return Number((stake / unitSize).toFixed(4));
}

function computeStreak(rows) {
  const settled = rows
    .filter((row) => row.deletedAt === null && (row.status === 'win' || row.status === 'loss'))
    .sort((left, right) => left.betNumber - right.betNumber);

  if (settled.length === 0) {
    return { type: 'none', count: 0 };
  }

  const last = settled[settled.length - 1].status;
  let count = 0;
  for (let index = settled.length - 1; index >= 0; index -= 1) {
    if (settled[index].status !== last) {
      break;
    }
    count += 1;
  }

  return { type: last, count };
}

function computeBestWorst(rows) {
  const settled = rows.filter((row) => row.deletedAt === null && row.profitLoss !== null);
  if (settled.length === 0) {
    return { best: null, worst: null };
  }

  const best = settled.reduce((top, row) => (row.profitLoss > top.profitLoss ? row : top), settled[0]);
  const worst = settled.reduce((low, row) => (row.profitLoss < low.profitLoss ? row : low), settled[0]);

  return { best, worst };
}

export class BetStore {
  constructor(databaseUrl, options = {}) {
    const usesSsl = /sslmode=(require|verify-ca|verify-full)/i.test(databaseUrl);
    this.pool = options.pool ?? new Pool({
      connectionString: databaseUrl,
      ssl: usesSsl ? { rejectUnauthorized: false } : undefined,
    });
  }

  async initialize() {
    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS users (
        discord_user_id TEXT PRIMARY KEY,
        username TEXT NOT NULL,
        display_name TEXT NOT NULL,
        next_bet_number INT NOT NULL DEFAULT 1,
        starting_bankroll DOUBLE PRECISION,
        unit_size DOUBLE PRECISION,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );
    `);

    await this.pool.query(`
      ALTER TABLE users ADD COLUMN IF NOT EXISTS username TEXT NOT NULL DEFAULT '';
      ALTER TABLE users ADD COLUMN IF NOT EXISTS display_name TEXT NOT NULL DEFAULT '';
      ALTER TABLE users ADD COLUMN IF NOT EXISTS next_bet_number INT NOT NULL DEFAULT 1;
      ALTER TABLE users ADD COLUMN IF NOT EXISTS starting_bankroll DOUBLE PRECISION;
      ALTER TABLE users ADD COLUMN IF NOT EXISTS unit_size DOUBLE PRECISION;
      ALTER TABLE users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
      ALTER TABLE users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS bets (
        id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        discord_user_id TEXT NOT NULL REFERENCES users(discord_user_id),
        bet_number INT NOT NULL,
        book TEXT NOT NULL,
        sport TEXT NOT NULL DEFAULT 'Other',
        odds_input TEXT NOT NULL,
        normalized_decimal_odds DOUBLE PRECISION NOT NULL,
        prop TEXT NOT NULL,
        stake DOUBLE PRECISION NOT NULL,
        units_value DOUBLE PRECISION,
        status TEXT NOT NULL DEFAULT 'open',
        profit_loss DOUBLE PRECISION,
        raw_input TEXT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        resolved_at TIMESTAMPTZ,
        deleted_at TIMESTAMPTZ,
        deleted_reason TEXT,
        CONSTRAINT bets_user_bet_number_unique UNIQUE (discord_user_id, bet_number)
      );
    `);

    await this.pool.query(`
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS discord_user_id TEXT;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS bet_number INT;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS book TEXT;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS sport TEXT NOT NULL DEFAULT 'Other';
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS odds_input TEXT;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS normalized_decimal_odds DOUBLE PRECISION;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS prop TEXT;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS stake DOUBLE PRECISION;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS units_value DOUBLE PRECISION;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'open';
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS profit_loss DOUBLE PRECISION;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS raw_input TEXT;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS resolved_at TIMESTAMPTZ;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
      ALTER TABLE bets ADD COLUMN IF NOT EXISTS deleted_reason TEXT;
    `);

    await this.pool.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS bets_user_bet_number_unique
      ON bets (discord_user_id, bet_number);
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS scan_runs (
        id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        scan_type TEXT NOT NULL,
        status TEXT NOT NULL DEFAULT 'completed',
        captured_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        entry_count INT NOT NULL DEFAULT 0,
        error_text TEXT
      );
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS scan_markets (
        id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        scan_run_id INT NOT NULL REFERENCES scan_runs(id) ON DELETE CASCADE,
        market_key TEXT NOT NULL,
        source TEXT NOT NULL,
        book TEXT NOT NULL,
        event_name TEXT,
        event_commence_time TIMESTAMPTZ,
        player_name TEXT NOT NULL,
        market_type TEXT NOT NULL,
        market_label TEXT NOT NULL,
        side TEXT NOT NULL,
        line_value DOUBLE PRECISION,
        odds_input TEXT NOT NULL,
        implied_probability DOUBLE PRECISION NOT NULL,
        raw_label TEXT,
        captured_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );
    `);

    await this.pool.query(`
      ALTER TABLE scan_markets ADD COLUMN IF NOT EXISTS event_commence_time TIMESTAMPTZ;
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS scan_reports (
        id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        report_date DATE NOT NULL,
        report_type TEXT NOT NULL,
        channel_id TEXT NOT NULL,
        primary_message_id TEXT,
        secondary_message_id TEXT,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        CONSTRAINT scan_reports_date_type_unique UNIQUE (report_date, report_type)
      );
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS scan_alerts (
        alert_key TEXT PRIMARY KEY,
        last_sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS circa_snapshots (
        id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        file_name TEXT NOT NULL,
        file_source TEXT,
        fingerprint TEXT NOT NULL UNIQUE,
        file_date DATE,
        seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        entry_count INT NOT NULL DEFAULT 0
      );
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS circa_snapshot_entries (
        id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        snapshot_id INT NOT NULL REFERENCES circa_snapshots(id) ON DELETE CASCADE,
        market_key TEXT NOT NULL,
        player_name TEXT NOT NULL,
        team TEXT,
        market_type TEXT NOT NULL,
        market_label TEXT NOT NULL,
        side TEXT NOT NULL,
        line_value DOUBLE PRECISION,
        odds_input TEXT NOT NULL,
        implied_probability DOUBLE PRECISION NOT NULL,
        raw_label TEXT
      );
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS circa_daily_posts (
        post_date DATE PRIMARY KEY,
        snapshot_id INT NOT NULL REFERENCES circa_snapshots(id),
        channel_id TEXT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );
    `);

    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS circa_movement_posts (
        movement_key TEXT PRIMARY KEY,
        last_snapshot_fingerprint TEXT NOT NULL,
        last_sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );
    `);
  }

  async upsertUser(user) {
    await this.pool.query(
      `
        INSERT INTO users (discord_user_id, username, display_name)
        VALUES ($1, $2, $3)
        ON CONFLICT (discord_user_id) DO UPDATE SET
          username = EXCLUDED.username,
          display_name = EXCLUDED.display_name,
          updated_at = NOW()
      `,
      [user.id, user.username, user.displayName ?? user.username]
    );
  }

  async getUserProfile(userId) {
    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM users
        WHERE discord_user_id = $1
      `,
      [userId]
    );

    if (!rows[0]) {
      return {
        startingBankroll: null,
        unitSize: null,
      };
    }

    return {
      startingBankroll: numberOrNull(rows[0].starting_bankroll),
      unitSize: numberOrNull(rows[0].unit_size),
    };
  }

  async updateUserPerformanceConfig(user, settings) {
    await this.upsertUser(user);
    const current = await this.getUserProfile(user.id);
    const startingBankroll = settings.startingBankroll ?? current.startingBankroll;
    const unitSize = settings.unitSize ?? current.unitSize;

    await this.pool.query(
      `
        UPDATE users
        SET starting_bankroll = $2,
            unit_size = $3,
            username = $4,
            display_name = $5,
            updated_at = NOW()
        WHERE discord_user_id = $1
      `,
      [user.id, startingBankroll, unitSize, user.username, user.displayName ?? user.username]
    );

    if (unitSize !== null && unitSize > 0) {
      await this.pool.query(
        `
          UPDATE bets
          SET units_value = stake / $2
          WHERE discord_user_id = $1
        `,
        [user.id, unitSize]
      );
    }

    return this.getUserProfile(user.id);
  }

  async createBet(user, bet) {
    const client = await this.pool.connect();

    try {
      await client.query('BEGIN');
      await client.query(
        `
          INSERT INTO users (discord_user_id, username, display_name)
          VALUES ($1, $2, $3)
          ON CONFLICT (discord_user_id) DO UPDATE SET
            username = EXCLUDED.username,
            display_name = EXCLUDED.display_name,
            updated_at = NOW()
        `,
        [user.id, user.username, user.displayName ?? user.username]
      );

      const { rows: userRows } = await client.query(
        `
          SELECT unit_size
          FROM users
          WHERE discord_user_id = $1
        `,
        [user.id]
      );
      const unitSize = numberOrNull(userRows[0]?.unit_size);
      const unitsValue = unitSize && unitSize > 0 ? deriveUnitsValue(bet.stake, unitSize) : 0;

      const { rows: counterRows } = await client.query(
        `
          UPDATE users
          SET next_bet_number = next_bet_number + 1,
              username = $2,
              display_name = $3,
              updated_at = NOW()
          WHERE discord_user_id = $1
          RETURNING next_bet_number - 1 AS bet_number
        `,
        [user.id, user.username, user.displayName ?? user.username]
      );
      const betNumber = Number(counterRows[0].bet_number);

      await client.query(
        `
          INSERT INTO bets (
            discord_user_id,
            bet_number,
            book,
            sport,
            odds_input,
            normalized_decimal_odds,
            prop,
            stake,
            units_value,
            raw_input
          )
          VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
        `,
        [
          user.id,
          betNumber,
          bet.book,
          bet.sport,
          bet.oddsInput,
          bet.normalizedDecimalOdds,
          bet.prop,
          bet.stake,
          unitsValue,
          bet.rawInput,
        ]
      );

      await client.query('COMMIT');
      return this.findBet(user.id, betNumber);
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

  async findBet(userId, betNumber, options = {}) {
    const includeDeleted = options.includeDeleted ?? true;
    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM bets
        WHERE discord_user_id = $1 AND bet_number = $2
        ${includeDeleted ? '' : 'AND deleted_at IS NULL'}
      `,
      [userId, betNumber]
    );

    return mapBet(rows[0]);
  }

  async updateBet(userId, betNumber, patch) {
    const existingBet = await this.findBet(userId, betNumber);
    if (!existingBet) {
      return { type: 'missing' };
    }

    if (existingBet.deletedAt) {
      return { type: 'deleted', bet: existingBet };
    }

    const attemptsFinancialEdit = [
      patch.oddsInput,
      patch.normalizedDecimalOdds,
      patch.stake,
      patch.unitsValue,
    ].some((value) => value !== undefined);

    if (existingBet.status !== 'open' && attemptsFinancialEdit) {
      return { type: 'financial_locked', bet: existingBet };
    }

    const updates = [];
    const values = [];
    let index = 1;

    for (const [column, value] of Object.entries({
      book: patch.book,
      sport: patch.sport,
      prop: patch.prop,
      odds_input: patch.oddsInput,
      normalized_decimal_odds: patch.normalizedDecimalOdds,
      stake: patch.stake,
      units_value: patch.unitsValue,
      raw_input: patch.rawInput,
    })) {
      if (value !== undefined) {
        updates.push(`${column} = $${index++}`);
        values.push(value);
      }
    }

    if (updates.length === 0) {
      return { type: 'no_changes', bet: existingBet };
    }

    values.push(userId, betNumber);
    await this.pool.query(
      `
        UPDATE bets
        SET ${updates.join(', ')}
        WHERE discord_user_id = $${index++} AND bet_number = $${index} AND deleted_at IS NULL
      `,
      values
    );

    return { type: 'updated', bet: await this.findBet(userId, betNumber) };
  }

  async softDeleteBet(userId, betNumber, reason = null) {
    const existingBet = await this.findBet(userId, betNumber);
    if (!existingBet) {
      return { type: 'missing' };
    }

    if (existingBet.deletedAt) {
      return { type: 'already_deleted', bet: existingBet };
    }

    await this.pool.query(
      `
        UPDATE bets
        SET deleted_at = NOW(),
            deleted_reason = $3
        WHERE discord_user_id = $1 AND bet_number = $2
      `,
      [userId, betNumber, reason]
    );

    return { type: 'deleted', bet: await this.findBet(userId, betNumber) };
  }

  async resolveBet(userId, betNumber, result) {
    const existingBet = await this.findBet(userId, betNumber);
    if (!existingBet) {
      return { type: 'missing' };
    }

    if (existingBet.deletedAt) {
      return { type: 'deleted', bet: existingBet };
    }

    if (existingBet.status !== 'open') {
      return { type: 'already_resolved', bet: existingBet };
    }

    const profitLoss = calculateProfitLoss(existingBet.stake, existingBet.normalizedDecimalOdds, result);
    await this.pool.query(
      `
        UPDATE bets
        SET status = $1, profit_loss = $2, resolved_at = NOW()
        WHERE discord_user_id = $3 AND bet_number = $4 AND status = 'open' AND deleted_at IS NULL
      `,
      [result, profitLoss, userId, betNumber]
    );

    return { type: 'resolved', bet: await this.findBet(userId, betNumber) };
  }

  async getBetRows(userId, filters = {}, options = {}) {
    const { clause, values } = buildWhereClause({ ...filters, userId }, options);
    const limitClause = options.limit ? ` LIMIT ${Number(options.limit)}` : '';
    const offsetClause = options.offset ? ` OFFSET ${Number(options.offset)}` : '';
    const orderClause = options.orderBy ?? 'bet_number DESC';

    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM bets
        WHERE ${clause}
        ORDER BY ${orderClause}
        ${limitClause}
        ${offsetClause}
      `,
      values
    );

    return rows.map(mapBet);
  }

  async getFilteredCount(userId, filters = {}, options = {}) {
    const { clause, values } = buildWhereClause({ ...filters, userId }, options);
    const { rows } = await this.pool.query(
      `
        SELECT COUNT(*) AS count
        FROM bets
        WHERE ${clause}
      `,
      values
    );

    return Number(rows[0].count ?? 0);
  }

  async getUserSummary(userId, filters = {}) {
    const rows = await this.getBetRows(userId, filters, { orderBy: 'bet_number ASC' });
    const profile = await this.getUserProfile(userId);
    const analytics = computeAnalytics(rows, profile);
    const streak = computeStreak(rows);
    const { best, worst } = computeBestWorst(rows);

    return {
      ...analytics,
      streak,
      bestBet: best,
      worstBet: worst,
    };
  }

  async getRecentBets(userId, filters = {}, page = 1, limit = 5) {
    const offset = Math.max(0, page - 1) * limit;
    const bets = await this.getBetRows(userId, filters, {
      limit,
      offset,
      orderBy: 'bet_number DESC',
      includeDeleted: filters.status === 'deleted',
    });
    const totalCount = await this.getFilteredCount(userId, filters, {
      includeDeleted: filters.status === 'deleted',
    });

    return {
      bets,
      totalCount,
      currentPage: page,
      totalPages: Math.max(1, Math.ceil(totalCount / limit)),
    };
  }

  async getChartPoints(userId, filters = {}) {
    const rows = await this.getBetRows(userId, filters, { orderBy: 'bet_number ASC' });
    let runningProfit = 0;

    return rows
      .filter((row) => row.deletedAt === null && row.status !== 'open')
      .map((row) => {
        runningProfit += Number(row.profitLoss ?? 0);
        return {
          betNumber: row.betNumber,
          status: row.status,
          profitLoss: Number(row.profitLoss ?? 0),
          runningProfit,
          label: `#${row.betNumber}`,
        };
      });
  }

  async getBookBreakdown(userId, filters = {}) {
    const rows = await this.getBetRows(userId, filters, { orderBy: 'bet_number ASC' });
    return computeGroupedBreakdown(rows, 'book');
  }

  async getSportBreakdown(userId, filters = {}) {
    const rows = await this.getBetRows(userId, filters, { orderBy: 'bet_number ASC' });
    return computeGroupedBreakdown(rows, 'sport');
  }

  async exportBets(userId, filters = {}) {
    return this.getBetRows(userId, filters, {
      orderBy: 'bet_number ASC',
      includeDeleted: filters.status === 'deleted',
    });
  }

  async recordMarketSnapshot(scanType, entries) {
    const client = await this.pool.connect();

    try {
      await client.query('BEGIN');
      const { rows } = await client.query(
        `
          INSERT INTO scan_runs (scan_type, status, entry_count)
          VALUES ($1, 'completed', $2)
          RETURNING id
        `,
        [scanType, entries.length]
      );
      const scanRunId = Number(rows[0].id);

      for (const entry of entries) {
        await client.query(
          `
            INSERT INTO scan_markets (
              scan_run_id,
              market_key,
              source,
              book,
              event_name,
              event_commence_time,
              player_name,
              market_type,
              market_label,
              side,
              line_value,
              odds_input,
              implied_probability,
              raw_label
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
          `,
          [
            scanRunId,
            entry.marketKey,
            entry.source,
            entry.book,
            entry.eventName,
            entry.eventCommenceTime ?? null,
            entry.playerName,
            entry.marketType,
            entry.marketLabel,
            entry.side,
            entry.lineValue,
            entry.oddsInput,
            entry.impliedProbability,
            entry.rawLabel,
          ]
        );
      }

      await client.query('COMMIT');
      return scanRunId;
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

  async getScanRunById(scanRunId) {
    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM scan_runs
        WHERE id = $1
        LIMIT 1
      `,
      [scanRunId]
    );

    if (!rows[0]) {
      return null;
    }

    const run = rows[0];
    const entriesResult = await this.pool.query(
      `
        SELECT *
        FROM scan_markets
        WHERE scan_run_id = $1
        ORDER BY player_name, market_type, side, line_value NULLS FIRST, book
      `,
      [scanRunId]
    );

    return {
      id: Number(run.id),
      scanType: run.scan_type,
      status: run.status,
      entryCount: Number(run.entry_count ?? 0),
      createdAt: run.created_at?.toISOString?.() ?? String(run.created_at),
      errorText: run.error_text ?? null,
      entries: entriesResult.rows.map((entry) => ({
        marketKey: entry.market_key,
        source: entry.source,
        book: entry.book,
        eventName: entry.event_name,
        eventCommenceTime: entry.event_commence_time?.toISOString?.() ?? (entry.event_commence_time ? String(entry.event_commence_time) : null),
        playerName: entry.player_name,
        marketType: entry.market_type,
        marketLabel: entry.market_label,
        side: entry.side,
        lineValue: numberOrNull(entry.line_value),
        oddsInput: entry.odds_input,
        impliedProbability: Number(entry.implied_probability),
        rawLabel: entry.raw_label ?? null,
      })),
    };
  }

  async getLatestScanRun(scanType = null) {
    const { rows } = await this.pool.query(
      `
        SELECT id
        FROM scan_runs
        ${scanType ? 'WHERE scan_type = $1' : ''}
        ORDER BY created_at DESC, id DESC
        LIMIT 1
      `,
      scanType ? [scanType] : []
    );

    if (!rows[0]) {
      return null;
    }

    return this.getScanRunById(Number(rows[0].id));
  }

  async getPreviousScanRun(scanRunId, scanType = null) {
    const { rows } = await this.pool.query(
      `
        SELECT id
        FROM scan_runs
        WHERE id < $1
        ${scanType ? 'AND scan_type = $2' : ''}
        ORDER BY id DESC
        LIMIT 1
      `,
      scanType ? [scanRunId, scanType] : [scanRunId]
    );

    if (!rows[0]) {
      return null;
    }

    return this.getScanRunById(Number(rows[0].id));
  }

  async hasScanReport(reportDate, reportType) {
    const { rows } = await this.pool.query(
      `
        SELECT 1
        FROM scan_reports
        WHERE report_date = $1 AND report_type = $2
      `,
      [reportDate, reportType]
    );

    return Boolean(rows[0]);
  }

  async recordScanReport(reportDate, reportType, channelId, primaryMessageId, secondaryMessageId = null) {
    await this.pool.query(
      `
        INSERT INTO scan_reports (report_date, report_type, channel_id, primary_message_id, secondary_message_id)
        VALUES ($1, $2, $3, $4, $5)
        ON CONFLICT (report_date, report_type) DO UPDATE SET
          channel_id = EXCLUDED.channel_id,
          primary_message_id = EXCLUDED.primary_message_id,
          secondary_message_id = EXCLUDED.secondary_message_id,
          created_at = NOW()
      `,
      [reportDate, reportType, channelId, primaryMessageId, secondaryMessageId]
    );
  }

  async canSendScanAlert(alertKey, cooldownMinutes) {
    const { rows } = await this.pool.query(
      `
        SELECT last_sent_at
        FROM scan_alerts
        WHERE alert_key = $1
      `,
      [alertKey]
    );

    if (!rows[0]) {
      return true;
    }

    const lastSentAt = new Date(rows[0].last_sent_at);
    return Date.now() - lastSentAt.getTime() >= cooldownMinutes * 60 * 1000;
  }

  async recordScanAlert(alertKey) {
    await this.pool.query(
      `
        INSERT INTO scan_alerts (alert_key, last_sent_at)
        VALUES ($1, NOW())
        ON CONFLICT (alert_key) DO UPDATE SET
          last_sent_at = NOW()
      `,
      [alertKey]
    );
  }

  async getLatestCircaSnapshot() {
    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM circa_snapshots
        ORDER BY seen_at DESC
        LIMIT 1
      `
    );

    if (!rows[0]) {
      return null;
    }

    return this.getCircaSnapshotById(Number(rows[0].id));
  }

  async getPreviousCircaSnapshot(snapshotId) {
    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM circa_snapshots
        WHERE id < $1
        ORDER BY id DESC
        LIMIT 1
      `,
      [snapshotId]
    );

    if (!rows[0]) {
      return null;
    }

    return this.getCircaSnapshotById(Number(rows[0].id));
  }

  async getCircaSnapshotByFingerprint(fingerprint) {
    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM circa_snapshots
        WHERE fingerprint = $1
        LIMIT 1
      `,
      [fingerprint]
    );

    if (!rows[0]) {
      return null;
    }

    return this.getCircaSnapshotById(Number(rows[0].id));
  }

  async getCircaSnapshotById(snapshotId) {
    const { rows } = await this.pool.query(
      `
        SELECT *
        FROM circa_snapshots
        WHERE id = $1
        LIMIT 1
      `,
      [snapshotId]
    );

    if (!rows[0]) {
      return null;
    }

    const snapshotRow = rows[0];
    const entryResult = await this.pool.query(
      `
        SELECT *
        FROM circa_snapshot_entries
        WHERE snapshot_id = $1
        ORDER BY market_label, player_name, side, line_value NULLS FIRST
      `,
      [snapshotId]
    );

    return {
      id: Number(snapshotRow.id),
      fileName: snapshotRow.file_name,
      fileSource: snapshotRow.file_source,
      fingerprint: snapshotRow.fingerprint,
      fileDate: snapshotRow.file_date ? new Date(snapshotRow.file_date).toISOString().slice(0, 10) : null,
      seenAt: snapshotRow.seen_at?.toISOString?.() ?? String(snapshotRow.seen_at),
      entryCount: Number(snapshotRow.entry_count),
      entries: entryResult.rows.map((entry) => ({
        marketKey: entry.market_key,
        source: 'circa',
        book: 'Circa',
        eventName: 'Circa MLB',
        eventId: null,
        playerName: entry.player_name,
        team: entry.team,
        marketType: entry.market_type,
        marketLabel: entry.market_label,
        side: entry.side,
        lineValue: numberOrNull(entry.line_value),
        oddsInput: entry.odds_input,
        impliedProbability: Number(entry.implied_probability),
        rawLabel: entry.raw_label,
      })),
    };
  }

  async recordCircaSnapshot(snapshot) {
    const existing = await this.getCircaSnapshotByFingerprint(snapshot.fingerprint);
    if (existing) {
      return existing;
    }

    const client = await this.pool.connect();

    try {
      await client.query('BEGIN');
      const { rows } = await client.query(
        `
          INSERT INTO circa_snapshots (file_name, file_source, fingerprint, file_date, entry_count)
          VALUES ($1, $2, $3, $4, $5)
          ON CONFLICT (fingerprint) DO NOTHING
          RETURNING id
        `,
        [
          snapshot.fileName,
          snapshot.fileSource ?? null,
          snapshot.fingerprint,
          snapshot.fileDate ?? null,
          snapshot.entries.length,
        ]
      );
      if (!rows[0]) {
        await client.query('ROLLBACK');
        return this.getCircaSnapshotByFingerprint(snapshot.fingerprint);
      }

      const snapshotId = Number(rows[0].id);

      for (const entry of snapshot.entries) {
        await client.query(
          `
            INSERT INTO circa_snapshot_entries (
              snapshot_id,
              market_key,
              player_name,
              team,
              market_type,
              market_label,
              side,
              line_value,
              odds_input,
              implied_probability,
              raw_label
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
          `,
          [
            snapshotId,
            entry.marketKey,
            entry.playerName,
            entry.team ?? null,
            entry.marketType,
            entry.marketLabel,
            entry.side,
            entry.lineValue ?? null,
            entry.oddsInput,
            entry.impliedProbability,
            entry.rawLabel ?? null,
          ]
        );
      }

      await client.query('COMMIT');
      return this.getCircaSnapshotById(snapshotId);
    } catch (error) {
      await client.query('ROLLBACK');
      if (error?.code === '23505') {
        return this.getCircaSnapshotByFingerprint(snapshot.fingerprint);
      }
      throw error;
    } finally {
      client.release();
    }
  }

  async getCircaDailyPost(postDate) {
    const { rows } = await this.pool.query(
      `
        SELECT post_date, snapshot_id, channel_id, created_at
        FROM circa_daily_posts
        WHERE post_date = $1
      `,
      [postDate]
    );

    if (!rows[0]) {
      return null;
    }

    return {
      postDate: rows[0].post_date?.toISOString?.().slice(0, 10) ?? String(rows[0].post_date),
      snapshotId: Number(rows[0].snapshot_id),
      channelId: rows[0].channel_id,
      createdAt: rows[0].created_at?.toISOString?.() ?? String(rows[0].created_at),
    };
  }

  async recordCircaDailyPost(postDate, snapshotId, channelId) {
    await this.pool.query(
      `
        INSERT INTO circa_daily_posts (post_date, snapshot_id, channel_id, created_at)
        VALUES ($1, $2, $3, NOW())
        ON CONFLICT (post_date) DO UPDATE SET
          snapshot_id = EXCLUDED.snapshot_id,
          channel_id = EXCLUDED.channel_id,
          created_at = NOW()
      `,
      [postDate, snapshotId, channelId]
    );
  }

  async getLatestCircaDailyPost() {
    const { rows } = await this.pool.query(
      `
        SELECT post_date, snapshot_id, channel_id, created_at
        FROM circa_daily_posts
        ORDER BY post_date DESC
        LIMIT 1
      `
    );

    if (!rows[0]) {
      return null;
    }

    return {
      postDate: rows[0].post_date?.toISOString?.().slice(0, 10) ?? String(rows[0].post_date),
      snapshotId: Number(rows[0].snapshot_id),
      channelId: rows[0].channel_id,
      createdAt: rows[0].created_at?.toISOString?.() ?? String(rows[0].created_at),
    };
  }

  async canSendCircaMovement(movementKey, fingerprint) {
    const { rows } = await this.pool.query(
      `
        SELECT last_snapshot_fingerprint
        FROM circa_movement_posts
        WHERE movement_key = $1
      `,
      [movementKey]
    );

    if (!rows[0]) {
      return true;
    }

    return rows[0].last_snapshot_fingerprint !== fingerprint;
  }

  async recordCircaMovement(movementKey, fingerprint) {
    await this.pool.query(
      `
        INSERT INTO circa_movement_posts (movement_key, last_snapshot_fingerprint, last_sent_at)
        VALUES ($1, $2, NOW())
        ON CONFLICT (movement_key) DO UPDATE SET
          last_snapshot_fingerprint = EXCLUDED.last_snapshot_fingerprint,
          last_sent_at = NOW()
      `,
      [movementKey, fingerprint]
    );
  }

  async close() {
    await this.pool.end();
  }
}

function computeGroupedBreakdown(rows, key) {
  const groups = new Map();

  for (const row of rows) {
    if (row.deletedAt) {
      continue;
    }

    const groupKey = row[key];
    if (!groups.has(groupKey)) {
      groups.set(groupKey, []);
    }
    groups.get(groupKey).push(row);
  }

  return [...groups.entries()].map(([label, groupRows]) => {
    const wins = groupRows.filter((row) => row.status === 'win').length;
    const losses = groupRows.filter((row) => row.status === 'loss').length;
    const voids = groupRows.filter((row) => row.status === 'void').length;
    const openBets = groupRows.filter((row) => row.status === 'open').length;
    const settledStake = groupRows
      .filter((row) => row.status === 'win' || row.status === 'loss')
      .reduce((total, row) => total + row.stake, 0);
    const netProfit = groupRows
      .filter((row) => row.status !== 'open')
      .reduce((total, row) => total + (row.profitLoss ?? 0), 0);
    const gradedBets = wins + losses;

    return {
      [key]: label,
      label,
      totalBets: groupRows.length,
      openBets,
      wins,
      losses,
      voids,
      settledStake,
      netProfit,
      roiPercent: settledStake > 0 ? (netProfit / settledStake) * 100 : 0,
      winRatePercent: gradedBets > 0 ? (wins / gradedBets) * 100 : 0,
    };
  });
}

export function calculateProfitLoss(stake, normalizedDecimalOdds, result) {
  if (result === 'win') {
    return Number((stake * (normalizedDecimalOdds - 1)).toFixed(2));
  }

  if (result === 'loss') {
    return Number((-stake).toFixed(2));
  }

  return 0;
}