File size: 31,820 Bytes
59b509f
d658b4f
77cc094
59b509f
 
 
a9b2951
4556eaf
59b509f
 
 
2fed52b
 
 
 
59b509f
 
fd68981
 
d658b4f
59b509f
a7f83b5
7ccf1cc
d658b4f
59b509f
a7f83b5
 
 
d658b4f
 
a7f83b5
59b509f
a7f83b5
 
d658b4f
a7f83b5
 
 
59b509f
d658b4f
 
 
 
 
 
 
 
59b509f
 
 
d658b4f
77cc094
a7f83b5
 
 
 
77cc094
d658b4f
77cc094
 
59b509f
 
d658b4f
 
59b509f
d658b4f
 
 
 
 
 
 
59b509f
d658b4f
59b509f
 
432a7e7
d658b4f
 
 
a9b2951
d658b4f
 
 
a9b2951
 
d658b4f
 
 
a9b2951
 
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
5277fde
432a7e7
5277fde
 
 
432a7e7
 
 
5277fde
432a7e7
 
 
 
 
 
5277fde
 
 
 
 
 
432a7e7
 
 
 
d658b4f
5277fde
 
 
7116561
5277fde
 
 
 
7116561
5277fde
7116561
 
 
 
5277fde
432a7e7
 
d658b4f
432a7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7116561
5277fde
 
432a7e7
 
d658b4f
5277fde
 
 
 
 
 
 
432a7e7
 
 
 
 
5277fde
432a7e7
 
 
 
 
 
5277fde
432a7e7
 
 
5277fde
432a7e7
 
 
7116561
5277fde
 
7116561
5277fde
7116561
5277fde
 
 
 
 
 
 
 
 
 
 
 
432a7e7
5277fde
 
 
 
 
 
 
 
 
432a7e7
 
d658b4f
 
5277fde
d658b4f
5277fde
 
7116561
 
d658b4f
 
a7f83b5
 
 
a9b2951
 
7116561
 
a7f83b5
d658b4f
 
 
a9b2951
 
d658b4f
 
a9b2951
d658b4f
 
 
a9b2951
 
 
a7f83b5
 
d658b4f
 
 
a7f83b5
 
a9b2951
 
d658b4f
 
 
a9b2951
 
 
 
 
5277fde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d658b4f
d9aa318
a7f83b5
 
d9aa318
 
 
 
 
 
 
 
5277fde
d9aa318
 
 
 
 
 
 
 
5277fde
d9aa318
 
 
 
 
 
5277fde
d9aa318
 
 
5277fde
d9aa318
 
 
 
 
 
 
 
 
 
 
 
 
5277fde
a7f83b5
d9aa318
 
 
 
 
 
 
 
 
 
 
 
5277fde
d9aa318
 
 
 
 
 
 
5277fde
a7f83b5
d9aa318
a7f83b5
 
 
d658b4f
 
a7f83b5
d658b4f
59b509f
 
 
d658b4f
59b509f
67d31ad
59b509f
 
 
d658b4f
59b509f
 
77cc094
 
7116561
a9b2951
d658b4f
 
d9aa318
d658b4f
 
 
 
 
 
a7f83b5
59b509f
d658b4f
59b509f
 
d658b4f
 
432a7e7
d658b4f
5277fde
 
 
 
 
 
 
 
 
 
a7f83b5
a9b2951
 
d9aa318
432a7e7
d9aa318
432a7e7
 
a9b2951
d9aa318
7116561
 
d658b4f
5277fde
 
d658b4f
5277fde
d658b4f
 
 
 
 
 
 
 
7116561
 
d658b4f
7116561
 
5277fde
a9b2951
 
5277fde
 
 
 
432a7e7
 
 
5277fde
432a7e7
d658b4f
432a7e7
d658b4f
d9aa318
432a7e7
a7f83b5
d658b4f
 
a9b2951
 
 
5277fde
432a7e7
5277fde
 
 
 
 
 
 
 
 
 
 
 
 
432a7e7
 
 
 
5277fde
a9b2951
d9aa318
a9b2951
 
 
 
d9aa318
a9b2951
7116561
d9aa318
a9b2951
d9aa318
a9b2951
 
 
 
 
 
 
7116561
432a7e7
7116561
d9aa318
 
d658b4f
 
a9b2951
 
432a7e7
a9b2951
 
 
5277fde
a9b2951
5277fde
d658b4f
a7f83b5
432a7e7
a9b2951
 
 
 
 
 
a7f83b5
a9b2951
 
 
 
 
 
 
d658b4f
a9b2951
 
5277fde
d658b4f
5277fde
 
 
 
 
 
 
 
 
 
 
 
 
d658b4f
432a7e7
d658b4f
 
a9b2951
 
 
 
a7f83b5
d658b4f
a7f83b5
a9b2951
d658b4f
 
 
a7f83b5
d658b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f83b5
d658b4f
a7f83b5
5277fde
d658b4f
5277fde
d658b4f
 
a9b2951
d9aa318
5277fde
d9aa318
 
 
 
 
a9b2951
d658b4f
a9b2951
 
 
 
 
d658b4f
a9b2951
7116561
a9b2951
 
 
 
 
 
d658b4f
 
 
 
a9b2951
d658b4f
 
d9aa318
a9b2951
d658b4f
a9b2951
d658b4f
 
a9b2951
 
d658b4f
a9b2951
 
59b509f
d658b4f
59b509f
 
 
7fe989f
6d4d78a
5277fde
d658b4f
77cc094
a7f83b5
d658b4f
 
 
1b10f03
d658b4f
 
77cc094
 
 
 
d658b4f
77cc094
 
 
 
 
5277fde
7116561
d658b4f
 
 
 
 
 
5277fde
d658b4f
 
 
 
5277fde
 
d658b4f
7116561
 
5277fde
7116561
 
77cc094
 
d658b4f
77cc094
 
 
 
 
d658b4f
e81cca9
 
db53307
2fed52b
 
e0ad870
59b509f
 
 
 
77cc094
59b509f
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
// paystack-webhook.js
// Node >= 14
// npm install express firebase-admin axios

const express = require('express');
const crypto = require('crypto');
const admin = require('firebase-admin');
const axios = require('axios');

const app = express();

// ----

// ----

const {
  FIREBASE_CREDENTIALS,
  PAYSTACK_DEMO_SECRET,
  PAYSTACK_LIVE_SECRET,
  PORT = 7860,
} = process.env;
const PAYSTACK_SECRET = PAYSTACK_DEMO_SECRET || PAYSTACK_LIVE_SECRET;

if (!PAYSTACK_SECRET) console.warn('WARNING: PAYSTACK secret not set.');

let db = null;
try {
  if (FIREBASE_CREDENTIALS) {
    const svc = JSON.parse(FIREBASE_CREDENTIALS);
    admin.initializeApp({ credential: admin.credential.cert(svc) });
    db = admin.firestore();
    console.log('Firebase admin initialized from FIREBASE_CREDENTIALS env var.');
  } else {
    if (!admin.apps.length) {
      console.warn('FIREBASE_CREDENTIALS not provided and admin not initialized.');
    } else {
      db = admin.firestore();
    }
  }
} catch (e) {
  console.error('Failed to init Firebase admin:', e);
}

/* -------------------- Helpers -------------------- */

function safeParseJSON(raw) {
  try { return JSON.parse(raw); } catch (e) { return null; }
}

function verifyPaystackSignature(rawBodyBuffer, signatureHeader) {
  if (!PAYSTACK_SECRET || !rawBodyBuffer || !signatureHeader) return false;
  try {
    const hmac = crypto.createHmac('sha512', PAYSTACK_SECRET);
    hmac.update(rawBodyBuffer);
    const expected = hmac.digest('hex');
    return crypto.timingSafeEqual(Buffer.from(expected, 'utf8'), Buffer.from(String(signatureHeader), 'utf8'));
  } catch (e) {
    console.error('Signature verification error:', e);
    return false;
  }
}

function extractSlugFromReferrer(refUrl) {
  if (!refUrl || typeof refUrl !== 'string') return null;
  try {
    const m = refUrl.match(/\/(?:pay|p)\/([^\/\?\#]+)/i);
    if (m && m[1]) return m[1];
    const parts = new URL(refUrl).pathname.split('/').filter(Boolean);
    if (parts.length) return parts[parts.length - 1];
  } catch (e) {
    const fallback = (refUrl.split('/').pop() || '').split('?')[0].split('#')[0];
    return fallback || null;
  }
  return null;
}

/* expiry helper */
const EXTRA_FREE_MS = 2 * 60 * 60 * 1000;
const WEEKLY_PLAN_IDS = new Set([3311892, 3305738, 'PLN_ngz4l76whecrpkv', 'PLN_f7a3oagrpt47d5f']);
const MONTHLY_PLAN_IDS = new Set([3305739, 'PLN_584ck56g65xhkum']);
function getExpiryFromPlan(planInput) {
  let interval = null, planId = null, planCode = null;
  if (!planInput) { interval = null; }
  else if (typeof planInput === 'object') {
    planId = planInput.id ?? planInput.plan_id ?? null;
    planCode = planInput.plan_code ?? planInput.planCode ?? null;
    interval = planInput.interval || planInput.billing_interval || null;
  } else if (typeof planInput === 'number') planId = planInput;
  else if (typeof planInput === 'string') { planCode = planInput; const asNum = Number(planInput); if (!Number.isNaN(asNum)) planId = asNum; }

  if (interval) {
    interval = String(interval).toLowerCase();
    if (interval.includes('week')) {
      const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
      return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
    }
    if (interval.includes('month')) {
      const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
      return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
    }
    if (interval.includes('hour')) {
      const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
      return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
    }
  }

  if (planId && WEEKLY_PLAN_IDS.has(planId)) {
    const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
    return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
  }
  if (planCode && WEEKLY_PLAN_IDS.has(planCode)) {
    const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
    return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
  }
  if (planId && MONTHLY_PLAN_IDS.has(planId)) {
    const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
    return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
  }
  if (planCode && MONTHLY_PLAN_IDS.has(planCode)) {
    const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
    return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
  }

  const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
}

/* -------------------- Mapping helpers & updates (SLUG-ONLY) -------------------- */

// update mapping doc by slug only (merge)
async function updateMappingWithIdentifiers(dbInstance, { slug, userId, userIdType, customerId, payerEmail, subscriptionCode, authorizationCode } = {}) {
  if (!dbInstance || !slug) return;
  try {
    const writeObj = {};
    if (userId !== undefined) writeObj.userId = String(userId);
    if (userIdType !== undefined) writeObj.userIdType = String(userIdType);
    if (customerId !== undefined && customerId !== null) writeObj.customerId = String(customerId);
    if (payerEmail !== undefined && payerEmail !== null) writeObj.payerEmail = String(payerEmail);
    if (subscriptionCode !== undefined && subscriptionCode !== null) writeObj.subscriptionCode = String(subscriptionCode);
    if (authorizationCode !== undefined && authorizationCode !== null) writeObj.authorizationCode = String(authorizationCode);
    if (Object.keys(writeObj).length === 0) return;

    await dbInstance.collection('paystack-page-mappings').doc(String(slug)).set({
      slug: String(slug),
      ...writeObj,
      updatedAt: admin.firestore.FieldValue.serverTimestamp(),
    }, { merge: true });
    console.log('Updated mapping doc (slug) with identifiers:', slug, writeObj);
  } catch (e) {
    console.error('updateMappingWithIdentifiers failed:', e);
  }
}

// get mapping doc data by slug (doc id)
async function getMappingBySlug(dbInstance, slug) {
  if (!dbInstance || !slug) return null;
  try {
    const ref = dbInstance.collection('paystack-page-mappings').doc(String(slug));
    const snap = await ref.get();
    if (!snap.exists) return null;
    return { ref, data: snap.data() };
  } catch (e) {
    console.error('getMappingBySlug error:', e);
    return null;
  }
}

// find mapping by other authoritative identifiers (customerId / payerEmail / subscriptionCode)
async function findMappingByIdentifiers(dbInstance, { customerId, payerEmail, subscriptionCode } = {}) {
  if (!dbInstance) return null;
  try {
    const coll = dbInstance.collection('paystack-page-mappings');
    if (customerId) {
      const q = await coll.where('customerId', '==', String(customerId)).limit(1).get();
      if (!q.empty) return { mappingDoc: q.docs[0].ref, data: q.docs[0].data() };
    }
    if (subscriptionCode) {
      const q2 = await coll.where('subscriptionCode', '==', String(subscriptionCode)).limit(1).get();
      if (!q2.empty) return { mappingDoc: q2.docs[0].ref, data: q2.docs[0].data() };
    }
    if (payerEmail) {
      const q3 = await coll.where('payerEmail', '==', String(payerEmail)).limit(1).get();
      if (!q3.empty) return { mappingDoc: q3.docs[0].ref, data: q3.docs[0].data() };
    }
    return null;
  } catch (e) {
    console.error('findMappingByIdentifiers error:', e);
    return null;
  }
}

// Resolve user doc from mapping: prefer slug doc, else mapping-by-identifiers
async function resolveUserDocFromMapping(dbInstance, { slug = null, customerId = null, payerEmail = null, subscriptionCode = null } = {}) {
  if (!dbInstance) return null;
  const usersRef = dbInstance.collection('users');

  // 1) try slug doc => read mapping.userId and resolve to users doc
  if (slug) {
    try {
      const mapping = await getMappingBySlug(dbInstance, slug);
      if (mapping && mapping.data && mapping.data.userId) {
        const mappedUserId = mapping.data.userId;
        // try doc id first
        try {
          const directRef = usersRef.doc(String(mappedUserId));
          const ds = await directRef.get();
          if (ds.exists) return directRef;
        } catch (e) {}
        // fallback: if mappedUserId looks like email
        if (String(mappedUserId).includes('@')) {
          try {
            const q = await usersRef.where('email', '==', String(mappedUserId)).limit(1).get();
            if (!q.empty) return q.docs[0].ref;
          } catch (e) {}
        }
        // fallback to other id fields
        const idFields = ['userId','uid','id'];
        for (const f of idFields) {
          try {
            const q = await usersRef.where(f,'==',mappedUserId).limit(1).get();
            if (!q.empty) return q.docs[0].ref;
          } catch (e) {}
        }
      }
    } catch (e) {
      console.error('resolveUserDocFromMapping slug branch error:', e);
    }
  }

  // 2) try mapping by identifiers
  try {
    const found = await findMappingByIdentifiers(dbInstance, { customerId, payerEmail, subscriptionCode });
    if (found && found.data && found.data.userId) {
      const mappedUserId = found.data.userId;
      // same resolution logic
      try {
        const directRef = usersRef.doc(String(mappedUserId));
        const ds = await directRef.get();
        if (ds.exists) return directRef;
      } catch (e) {}
      if (String(mappedUserId).includes('@')) {
        try {
          const q = await usersRef.where('email', '==', String(mappedUserId)).limit(1).get();
          if (!q.empty) return q.docs[0].ref;
        } catch (e) {}
      }
      const idFields = ['userId','uid','id'];
      for (const f of idFields) {
        try {
          const q = await usersRef.where(f,'==',mappedUserId).limit(1).get();
          if (!q.empty) return q.docs[0].ref;
        } catch (e) {}
      }
    }
  } catch (e) {
    console.error('resolveUserDocFromMapping identifiers branch error:', e);
  }

  return null;
}

/* -------------------- Fallback user resolution -------------------- */

async function findUserDocRef(dbInstance, { metadataUserId, email, paystackCustomerId } = {}) {
  if (!dbInstance) return null;
  const usersRef = dbInstance.collection('users');

  if (metadataUserId) {
    if (!String(metadataUserId).includes('@')) {
      try {
        const docRef = usersRef.doc(String(metadataUserId));
        const s = await docRef.get();
        if (s.exists) return docRef;
      } catch (e) {}
    }

    const idFields = ['userId','uid','id'];
    for (const f of idFields) {
      try {
        const q = await usersRef.where(f,'==',metadataUserId).limit(1).get();
        if (!q.empty) return q.docs[0].ref;
      } catch (e) {}
    }
  }

  if (paystackCustomerId) {
    try {
      const q = await usersRef.where('paystack_customer_id','==',String(paystackCustomerId)).limit(1).get();
      if (!q.empty) return q.docs[0].ref;
    } catch (e) {}
  }

  if (email) {
    try {
      const q = await usersRef.where('email','==',String(email)).limit(1).get();
      if (!q.empty) return q.docs[0].ref;
    } catch (e) {}
  }

  return null;
}

/* -------------------- Cleanup (SLUG-only + smarter owner check) -------------------- */

async function cleanUpAfterSuccessfulCharge(dbInstance, userDocRef, { slug, reference, email } = {}) {
  if (!dbInstance || !userDocRef) return;
  try {
    // load mapping only by slug (we no longer create pageId docs)
    if (!slug) return;
    const mapRef = dbInstance.collection('paystack-page-mappings').doc(String(slug));
    const mapSnap = await mapRef.get();
    if (!mapSnap.exists) return;
    const map = mapSnap.data();

    // determine mapping owner type and user identity
    const ownerVal = String(map.userId || '');
    const ownerType = map.userIdType || (ownerVal.includes('@') ? 'email' : 'uid');

    // get user doc data to check email or id
    const userSnap = await userDocRef.get();
    if (!userSnap.exists) return;
    const userData = userSnap.data() || {};
    const userEmail = userData.email || null;
    const userId = userDocRef.id;

    let shouldDelete = false;
    if (ownerType === 'uid' && ownerVal === userId) shouldDelete = true;
    if (ownerType === 'email' && userEmail && ownerVal === userEmail) shouldDelete = true;

    if (shouldDelete) {
      await mapRef.delete();
      console.log('Deleted mapping doc (slug) after successful charge:', slug);
    } else {
      console.log('Mapping owner mismatch — not deleting slug:', slug, 'mappingOwner=', ownerVal, 'ownerType=', ownerType, 'userId=', userId, 'userEmail=', userEmail);
    }
  } catch (e) {
    console.error('Error in cleanUpAfterSuccessfulCharge:', e);
  }
}

/* -------------------- Prune helper (optional, unchanged) -------------------- */

async function pruneUserEntitlementsAndWebhooks(dbInstance, userDocRef, { paystackCustomerId = null, payerEmail = null } = {}) {
  if (!dbInstance || !userDocRef) return;
  try {
    const cutoffMs = Date.now() - (60 * 24 * 60 * 60 * 1000);
    const snap = await userDocRef.get();
    if (!snap.exists) return;
    const userData = snap.data() || {};
    const entitlements = Array.isArray(userData.entitlements) ? userData.entitlements : [];
    const cleaned = entitlements.filter(e => {
      if (e && (e.expiresAtMs || e.expiresAtMs === 0)) {
        const exMs = Number(e.expiresAtMs) || 0;
        return exMs > Date.now();
      }
      if (e && e.createdAt) {
        let createdMs = 0;
        try {
          if (typeof e.createdAt === 'number') createdMs = e.createdAt;
          else if (e.createdAt && typeof e.createdAt.toMillis === 'function') createdMs = e.createdAt.toMillis();
          else if (typeof e.createdAt === 'string') createdMs = Number(e.createdAt) || 0;
          else if (e.createdAt._seconds) createdMs = (Number(e.createdAt._seconds) * 1000) + (Number(e.createdAt._nanoseconds || 0) / 1e6);
        } catch (ee) { createdMs = 0; }
        if (createdMs) return createdMs >= cutoffMs;
        return true;
      }
      return true;
    });
    if (cleaned.length !== entitlements.length) {
      await userDocRef.update({ entitlements: cleaned, updatedAt: admin.firestore.FieldValue.serverTimestamp() });
      console.log('Pruned entitlements: removed', entitlements.length - cleaned.length, 'entries for', userDocRef.path);
    }

    // prune paystack-webhooks older than cutoff for this user (best-effort)
    try {
      const coll = dbInstance.collection('paystack-webhooks');
      const toDeleteRefs = [];
      if (paystackCustomerId) {
        try {
          const q = await coll.where('payload.data.customer.id', '==', paystackCustomerId).get();
          q.docs.forEach(d => {
            const r = d.data();
            const ts = r.receivedAt;
            let tsMs = 0;
            if (ts && typeof ts.toMillis === 'function') tsMs = ts.toMillis();
            if (tsMs && tsMs < cutoffMs) toDeleteRefs.push(d.ref);
          });
        } catch (e) { console.warn('Could not query paystack-webhooks by customer.id (skipping):', e); }
      }
      if (payerEmail) {
        try {
          const q2 = await coll.where('payload.data.customer.email', '==', payerEmail).get();
          q2.docs.forEach(d => {
            const r = d.data();
            const ts = r.receivedAt;
            let tsMs = 0;
            if (ts && typeof ts.toMillis === 'function') tsMs = ts.toMillis();
            if (tsMs && tsMs < cutoffMs) {
              if (!toDeleteRefs.find(x => x.path === d.ref.path)) toDeleteRefs.push(d.ref);
            }
          });
        } catch (e) { console.warn('Could not query paystack-webhooks by customer.email (skipping):', e); }
      }
      if (toDeleteRefs.length) {
        const batch = dbInstance.batch();
        toDeleteRefs.forEach(r => batch.delete(r));
        await batch.commit();
        console.log('Deleted', toDeleteRefs.length, 'old paystack-webhooks audit docs for user', userDocRef.id);
      }
    } catch (e) { console.error('Failed pruning paystack-webhooks (non-fatal):', e); }
  } catch (e) {
    console.error('pruneUserEntitlementsAndWebhooks failed:', e);
  }
}

/* -------------------- Webhook route -------------------- */

app.post('/webhook/paystack', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res) => {
  const raw = req.body;
  const signature = req.get('x-paystack-signature') || req.get('X-Paystack-Signature');

  if (!signature || !verifyPaystackSignature(raw, signature)) {
    console.warn('Paystack webhook signature verify failed. header:', signature);
    return res.status(400).json({ ok: false, message: 'Invalid signature' });
  }

  const bodyStr = raw.toString('utf8');
  const payload = safeParseJSON(bodyStr);
  if (!payload) return res.status(400).json({ ok: false, message: 'Invalid JSON' });

  const event = (payload.event || payload.type || '').toString();
  const isRefund = /refund/i.test(event);
  const isChargeSuccess = /charge\.success/i.test(event);
  const isPayment = isChargeSuccess;

  if (!db) console.error('Firestore admin not initialized — cannot persist webhook data.');

  // persist webhook audit
  try {
    if (db) {
      await db.collection('paystack-webhooks').add({ event, payload, receivedAt: admin.firestore.FieldValue.serverTimestamp() });
    }
  } catch (e) {
    console.error('Failed to persist webhook audit:', e);
  }

  if (/subscription\.create/i.test(event) || isRefund || isPayment || /subscription\.update/i.test(event)) {
    console.log('--- PAYSTACK WEBHOOK (INTERESTING EVENT) ---');
    console.log('event:', event);
    const data = payload.data || {};

    // extract slug
    let maybeSlug = data.page?.slug || data.slug || null;
    if (!maybeSlug) {
      const referrer = data.metadata?.referrer || (data.metadata && data.metadata.referrer) || null;
      if (referrer) {
        const extracted = extractSlugFromReferrer(String(referrer));
        if (extracted) {
          maybeSlug = extracted;
          console.log('Extracted slug from metadata.referrer:', maybeSlug);
        } else {
          console.log('Could not extract slug from referrer:', referrer);
        }
      }
    }

    // authoritative identifiers
    const paystackCustomerId = data.customer?.id ?? data.customer?.customer_code ?? null;
    const payerEmail = data.customer?.email ?? null; // saved on mapping as payerEmail
    const subscriptionCode = data.subscription_code || data.subscription?.subscription_code || null;
    const authorizationCode = data.authorization?.authorization_code || data.authorization_code || null;

    // quick metadata extraction
    let metadataUserId = null;
    try {
      const metadata = data.metadata || {};
      if (metadata.userId || metadata.user_id) metadataUserId = metadata.userId || metadata.user_id;
      else if (data.customer?.metadata) {
        const cm = data.customer.metadata;
        if (cm.userId || cm.user_id) metadataUserId = cm.userId || cm.user_id;
      } else if (Array.isArray(data.custom_fields)) {
        for (const f of data.custom_fields) {
          const n = (f.variable_name || f.display_name || '').toString().toLowerCase();
          if ((n.includes('user') || n.includes('user_id') || n.includes('userid')) && f.value) {
            metadataUserId = f.value;
            break;
          }
        }
      }
    } catch (e) {
      console.error('Error during quick metadata extraction:', e);
    }

    // Resolve user: mapping-first (slug), then mapping-by-identifiers, then fallback queries
    let userDocRef = null;
    try {
      if (maybeSlug && db) {
        userDocRef = await resolveUserDocFromMapping(db, { slug: maybeSlug, customerId: paystackCustomerId, payerEmail, subscriptionCode });
        if (userDocRef) console.log('Resolved user from mapping (slug):', userDocRef.path, 'slug=', maybeSlug);
        else console.log('No mapping resolved from slug:', maybeSlug);
      }

      if (!userDocRef && db && (paystackCustomerId || payerEmail || subscriptionCode)) {
        userDocRef = await resolveUserDocFromMapping(db, { slug: null, customerId: paystackCustomerId, payerEmail, subscriptionCode });
        if (userDocRef) console.log('Resolved user from mapping by identifiers ->', userDocRef.path);
      }

      if (!userDocRef) {
        userDocRef = await findUserDocRef(db, { metadataUserId, email: payerEmail, paystackCustomerId });
        if (userDocRef) console.log('Resolved user via fallback queries:', userDocRef.path);
      }
    } catch (e) {
      console.error('Error resolving userDocRef (mapping-first):', e);
      userDocRef = null;
    }

    // update mapping with authoritative identifiers ONLY if we have a slug (we avoid creating mapping by pageId)
    try {
      if (maybeSlug) {
        const userIdToSave = metadataUserId || (userDocRef ? userDocRef.id : undefined);
        const userIdType = userIdToSave && String(userIdToSave).includes('@') ? 'email' : 'uid';
        await updateMappingWithIdentifiers(db, {
          slug: maybeSlug,
          userId: userIdToSave,
          userIdType,
          customerId: paystackCustomerId || undefined,
          payerEmail: payerEmail || undefined,
          subscriptionCode: subscriptionCode || undefined,
          authorizationCode: authorizationCode || undefined,
        });
      }
    } catch (e) {
      console.error('Failed updateMappingWithIdentifiers:', e);
    }

    // subscription.create
    if (/subscription\.create/i.test(event) || event === 'subscription.create') {
      const subscriptionCodeLocal = subscriptionCode || (data.id ? String(data.id) : null);
      const status = data.status || 'active';
      const planObj = data.plan || data.subscription?.plan || null;
      const expiry = getExpiryFromPlan(planObj);

      if (userDocRef && subscriptionCodeLocal) {
        try {
          const updateObj = {
            subscriptionId: subscriptionCodeLocal,
            subscription: {
              id: subscriptionCodeLocal,
              status,
              plan: planObj ? { id: planObj.id, code: planObj.plan_code, amount: planObj.amount, interval: planObj.interval } : null,
              createdAt: data.createdAt ? admin.firestore.Timestamp.fromDate(new Date(data.createdAt)) : admin.firestore.FieldValue.serverTimestamp(),
              expiresAtMs: expiry.expiresAtMs,
              expiresAtIso: expiry.expiresAtIso,
            },
            updatedAt: admin.firestore.FieldValue.serverTimestamp(),
          };
          if (paystackCustomerId) updateObj.paystack_customer_id = String(paystackCustomerId);
          await userDocRef.update(updateObj);
          console.log('subscription.create: updated user with subscription:', subscriptionCodeLocal);
          await pruneUserEntitlementsAndWebhooks(db, userDocRef, { paystackCustomerId, payerEmail });
        } catch (e) {
          console.error('subscription.create: failed to update user:', e);
        }
      } else {
        console.warn('subscription.create: user not found or subscriptionCode missing — skipping user update.');
      }
    }

    // charge.success
    if (isPayment) {
      console.log('charge.success identifiers:', { metadataUserId, payerEmail, maybeSlug, paystackCustomerId, subscriptionCode });

      const recurringMarker = Boolean((data.metadata && (data.metadata.custom_filters?.recurring || data.metadata.recurring)) || false);
      const hasSubscription = !!(data.subscription || data.subscriptions || data.plan || subscriptionCode);
      const isLikelySubscriptionPayment = recurringMarker || hasSubscription;

      const planObj = data.plan || (data.subscription ? data.subscription.plan : null) || null;
      const expiry = getExpiryFromPlan(planObj);

      const entitlement = {
        id: (data.reference || data.id) ? String(data.reference || data.id) : null,
        source: 'paystack',
        amount: data.amount || null,
        reference: data.reference || null,
        paidAt: data.paid_at || data.paidAt || data.created_at || null,
        plan: planObj ? { id: planObj.id, code: planObj.plan_code } : null,
        expiresAtMs: expiry.expiresAtMs,
        expiresAtIso: expiry.expiresAtIso,
        createdAt: admin.firestore.Timestamp.now(),
      };

      // Ensure mapping gets authoritative identifiers on first charge (only if slug present)
      try {
        if (maybeSlug) {
          const userIdToSave = metadataUserId || (userDocRef ? userDocRef.id : undefined);
          const userIdType = userIdToSave && String(userIdToSave).includes('@') ? 'email' : 'uid';
          await updateMappingWithIdentifiers(db, {
            slug: maybeSlug,
            userId: userIdToSave,
            userIdType,
            customerId: paystackCustomerId || undefined,
            payerEmail: payerEmail || undefined,
            subscriptionCode: subscriptionCode || undefined,
            authorizationCode: authorizationCode || undefined,
          });
        }
      } catch (e) {
        console.error('Failed updateMappingWithIdentifiers during charge.success:', e);
      }

      if (userDocRef && isLikelySubscriptionPayment) {
        try {
          await userDocRef.update({
            entitlements: admin.firestore.FieldValue.arrayUnion(entitlement),
            lastPaymentAt: admin.firestore.FieldValue.serverTimestamp(),
            updatedAt: admin.firestore.FieldValue.serverTimestamp(),
            ...(paystackCustomerId ? { paystack_customer_id: String(paystackCustomerId) } : {}),
          });
          console.log('Entitlement added (arrayUnion) to', userDocRef.path);
        } catch (err) {
          console.error('arrayUnion failed, falling back:', err);
          try {
            const snap = await userDocRef.get();
            const userData = snap.exists ? snap.data() : {};
            const current = Array.isArray(userData.entitlements) ? userData.entitlements : [];
            const exists = current.some(e => (e.reference || e.id) === (entitlement.reference || entitlement.id));
            if (!exists) {
              current.push(entitlement);
              await userDocRef.update({
                entitlements: current,
                lastPaymentAt: admin.firestore.FieldValue.serverTimestamp(),
                updatedAt: admin.firestore.FieldValue.serverTimestamp(),
                ...(paystackCustomerId ? { paystack_customer_id: String(paystackCustomerId) } : {}),
              });
              console.log('Entitlement appended via fallback.');
            } else {
              console.log('Entitlement already present, skipping append.');
            }
          } catch (err2) {
            console.error('Fallback persistence failed:', err2);
          }
        }

        // cleanup mapping doc if slug exists (only slug doc)
        try {
          await cleanUpAfterSuccessfulCharge(db, userDocRef, { slug: maybeSlug, reference: entitlement.reference || entitlement.id, email: payerEmail });
        } catch (e) {
          console.error('Cleanup failed:', e);
        }

        // prune entitlements & old webhooks
        try {
          await pruneUserEntitlementsAndWebhooks(db, userDocRef, { paystackCustomerId, payerEmail });
        } catch (e) {
          console.error('Prune helper failed:', e);
        }
      } else if (userDocRef && !isLikelySubscriptionPayment) {
        console.log('charge.success received but not flagged subscription/recurring - skipping entitlement add.');
      } else {
        console.warn('charge.success: user not found, skipping entitlement update.');
      }
    }

    // refunds
    if (isRefund) {
      const refund = data;
      const refundedReference = refund.reference || refund.transaction?.reference || refund.transaction?.id || null;
      if (userDocRef && refundedReference) {
        try {
          const snap = await userDocRef.get();
          if (snap.exists) {
            const userData = snap.data();
            const current = Array.isArray(userData.entitlements) ? userData.entitlements : [];
            const filtered = current.filter(e => {
              const r = e.reference || e.id || '';
              return r !== refundedReference && r !== String(refundedReference);
            });
            await userDocRef.update({ entitlements: filtered, updatedAt: admin.firestore.FieldValue.serverTimestamp() });
            console.log('Removed entitlements matching refund:', refundedReference);
            await pruneUserEntitlementsAndWebhooks(db, userDocRef, { paystackCustomerId, payerEmail });
          } else {
            console.warn('Refund handling: user doc vanished.');
          }
        } catch (e) {
          console.error('Refund entitlement removal failed:', e);
        }
      } else {
        console.warn('Refund: user or refundedReference missing; skipping.');
      }
    }
  } else {
    console.log('Ignoring event:', event);
  }

  return res.status(200).json({ ok: true });
});

/* -------------------- Create payment link endpoint (SLUG only) -------------------- */

app.post('/create-payment-link', express.json(), async (req, res) => {
  const { planId, userId, name, amount, redirect_url, collect_phone = false, fixed_amount = false } = req.body || {};
  if (!planId) return res.status(400).json({ ok: false, message: 'planId required' });
  if (!userId) return res.status(400).json({ ok: false, message: 'userId required' });
  if (!name) return res.status(400).json({ ok: false, message: 'name required' });

  const payload = { name, type: 'subscription', plan: planId, metadata: { userId: String(userId) }, collect_phone, fixed_amount };
  if (amount) payload.amount = amount;
  if (redirect_url) payload.redirect_url = redirect_url;

  try {
    const response = await axios.post('https://api.paystack.co/page', payload, {
      headers: { Authorization: `Bearer ${PAYSTACK_SECRET}`, 'Content-Type': 'application/json' },
      timeout: 10_000,
    });

    const pageData = response.data && response.data.data ? response.data.data : response.data;

    // persist mapping doc keyed by slug only (no pageId doc creation)
    try {
      if (db) {
        const slug = pageData.slug || pageData.data?.slug || null;
        if (slug) {
          await db.collection('paystack-page-mappings').doc(String(slug)).set({
            userId: String(userId),
            userIdType: String(userId).includes('@') ? 'email' : 'uid',
            pageId: pageData.id ? String(pageData.id) : null, // store pageId inside slug doc only
            slug: String(slug),
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
          }, { merge: true });
          console.log('Saved page slug mapping for', slug);
        } else {
          console.warn('create-payment-link: Paystack response did not return a slug; no mapping saved.');
        }
      }
    } catch (e) {
      console.error('Failed to persist mapping doc (slug only):', e);
    }

    return res.status(201).json({ ok: true, page: pageData });
  } catch (err) {
    console.error('Error creating Paystack page:', err?.response?.data || err.message || err);
    const errorDetail = err?.response?.data || { message: err.message };
    return res.status(500).json({ ok: false, error: errorDetail });
  }
});

/* health */
app.get('/health', (_req, res) => res.status(200).json({ ok: true }));
app.post('/health', (_req, res) => res.status(200).json({ ok: true }));

app.get('/', (_req, res) => res.status(204).end());
app.post('/', (_req, res) => res.status(204).end());


app.listen(PORT, () => {
  console.log(`Paystack webhook server listening on port ${PORT}`);
  console.log('POST /webhook/paystack to receive Paystack callbacks');
  console.log('POST /create-payment-link to create a subscription payment page (expects JSON body).');
});