File size: 26,465 Bytes
59b509f
d658b4f
77cc094
59b509f
 
 
a9b2951
 
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
 
d658b4f
 
 
 
a9b2951
d658b4f
 
 
a9b2951
 
d658b4f
 
 
a9b2951
 
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
a9b2951
 
 
d658b4f
 
 
a7f83b5
d658b4f
7116561
d658b4f
 
 
 
 
 
 
 
 
a7f83b5
d658b4f
a7f83b5
 
 
d658b4f
a7f83b5
 
 
7116561
d658b4f
7116561
 
 
 
d658b4f
 
 
 
 
 
 
7116561
d658b4f
 
 
 
 
 
 
 
 
7116561
d658b4f
 
7116561
 
d658b4f
 
 
 
 
 
 
 
 
 
 
7116561
d658b4f
 
 
 
 
 
 
 
 
 
 
7116561
d658b4f
 
 
 
 
7116561
 
d658b4f
 
a7f83b5
 
 
a9b2951
 
7116561
 
a7f83b5
d658b4f
 
 
a9b2951
 
d658b4f
 
a9b2951
d658b4f
 
 
a9b2951
 
 
a7f83b5
 
d658b4f
 
 
a7f83b5
 
a9b2951
 
d658b4f
 
 
a9b2951
 
 
 
 
d658b4f
 
a7f83b5
 
 
d658b4f
 
a7f83b5
d658b4f
 
 
 
 
 
 
 
 
 
a7f83b5
 
d658b4f
a7f83b5
d658b4f
 
 
a7f83b5
d658b4f
a7f83b5
 
d658b4f
a7f83b5
 
d658b4f
a7f83b5
 
 
 
d658b4f
a7f83b5
 
d658b4f
a7f83b5
 
 
 
d658b4f
a7f83b5
 
 
 
 
d658b4f
a7f83b5
 
d658b4f
a7f83b5
 
 
d658b4f
 
a7f83b5
d658b4f
59b509f
 
 
d658b4f
59b509f
67d31ad
59b509f
 
 
d658b4f
59b509f
 
77cc094
 
7116561
a9b2951
d658b4f
 
 
 
 
 
 
 
 
a7f83b5
59b509f
d658b4f
59b509f
 
d658b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f83b5
a9b2951
 
d658b4f
 
a9b2951
d658b4f
7116561
 
 
 
d658b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7116561
 
d658b4f
7116561
 
 
a7f83b5
 
d658b4f
a9b2951
 
d658b4f
 
 
 
 
 
 
 
 
a7f83b5
d658b4f
 
a9b2951
 
 
d658b4f
a9b2951
 
 
 
 
d658b4f
a9b2951
 
 
7116561
a9b2951
 
 
 
 
 
 
 
 
 
7116561
d658b4f
7116561
d658b4f
 
 
a9b2951
 
 
 
 
 
d658b4f
a9b2951
d658b4f
 
a7f83b5
7116561
a9b2951
 
 
 
 
 
a7f83b5
a9b2951
 
 
 
 
 
 
d658b4f
a9b2951
 
d658b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9b2951
 
d658b4f
a9b2951
 
a7f83b5
d658b4f
a7f83b5
a9b2951
d658b4f
 
 
 
a7f83b5
d658b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f83b5
d658b4f
a7f83b5
d658b4f
 
 
 
 
a9b2951
 
d658b4f
a9b2951
 
d658b4f
 
 
 
 
 
 
 
 
 
 
a9b2951
 
 
d658b4f
a9b2951
7116561
a9b2951
 
 
 
 
 
d658b4f
 
 
 
a9b2951
d658b4f
 
a9b2951
d658b4f
a9b2951
d658b4f
 
a9b2951
 
d658b4f
a9b2951
 
59b509f
d658b4f
59b509f
 
 
7fe989f
6d4d78a
d658b4f
 
77cc094
a7f83b5
d658b4f
 
 
1b10f03
d658b4f
 
77cc094
 
 
 
d658b4f
77cc094
 
 
 
 
d658b4f
7116561
d658b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7116561
 
d658b4f
7116561
 
77cc094
 
d658b4f
77cc094
 
 
 
 
d658b4f
 
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
// 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;
  // common patterns: https://paystack.shop/pay/<slug>, https://example.com/pay/<slug>?...
  try {
    // quick regex: look for /pay/<slug> or /p/<slug>
    const m = refUrl.match(/\/(?:pay|p)\/([^\/\?\#]+)/i);
    if (m && m[1]) return m[1];
    // fallback: last path segment
    const parts = new URL(refUrl).pathname.split('/').filter(Boolean);
    if (parts.length) return parts[parts.length - 1];
  } catch (e) {
    // invalid URL string; try fallback heuristic
    const fallback = (refUrl.split('/').pop() || '').split('?')[0].split('#')[0];
    return fallback || null;
  }
  return null;
}

/* expiry helper (same as before) */
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 resolution helpers -------------------- */

// get userId string from mapping doc (doc id == slug or where pageId==slug)
async function getUserIdFromSlug(dbInstance, slugOrPageId) {
  if (!dbInstance || !slugOrPageId) return null;
  try {
    // doc id lookup
    const docRef = dbInstance.collection('paystack-page-mappings').doc(String(slugOrPageId));
    const snap = await docRef.get();
    if (snap.exists) {
      const d = snap.data();
      if (d?.userId) {
        console.log('Found mapping doc (by docId) for', slugOrPageId, ':', d);
        return d.userId;
      }
    }
    // fallback query by pageId
    const q = await dbInstance.collection('paystack-page-mappings').where('pageId', '==', String(slugOrPageId)).limit(1).get();
    if (!q.empty) {
      const d = q.docs[0].data();
      console.log('Found mapping doc (by pageId) for', slugOrPageId, ':', d);
      if (d?.userId) return d.userId;
    }
    return null;
  } catch (e) {
    console.error('getUserIdFromSlug error:', e);
    return null;
  }
}

// Attempt resolution: given mapping key (slug), return a users/<docRef> or null
async function resolveUserDocFromMapping(dbInstance, key) {
  if (!dbInstance || !key) return null;
  try {
    // map to userId (string) first
    const mappedUserId = await getUserIdFromSlug(dbInstance, key);
    if (!mappedUserId) return null;

    const usersRef = dbInstance.collection('users');

    // try doc id first
    try {
      const directRef = usersRef.doc(String(mappedUserId));
      const ds = await directRef.get();
      if (ds.exists) {
        console.log('Resolved user by direct doc id:', directRef.path);
        return directRef;
      }
    } catch (e) {
      // continue to queries
    }

    // if mappedUserId looks like email, try email query
    const looksLikeEmail = String(mappedUserId).includes('@');
    if (looksLikeEmail) {
      try {
        const q = await usersRef.where('email', '==', String(mappedUserId)).limit(1).get();
        if (!q.empty) {
          console.log('Resolved user by email query for', mappedUserId);
          return q.docs[0].ref;
        }
      } catch (e) { /* ignore */ }
    }

    // fallback to common 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) {
          console.log('Resolved user by field', f, 'for', mappedUserId);
          return q.docs[0].ref;
        }
      } catch (e) { /* ignore */ }
    }

    return null;
  } catch (e) {
    console.error('resolveUserDocFromMapping 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 -------------------- */

async function cleanUpAfterSuccessfulCharge(dbInstance, userDocRef, { slug, pageId, reference, email } = {}) {
  if (!dbInstance || !userDocRef) return;
  try {
    const tryDelete = async (docId) => {
      if (!docId) return;
      try {
        const ref = dbInstance.collection('paystack-page-mappings').doc(String(docId));
        const s = await ref.get();
        if (!s.exists) return;
        const map = s.data();
        const owner = String(map.userId || '');
        if (owner === String(userDocRef.id) || (email && owner === String(email))) {
          await ref.delete();
          console.log('Deleted mapping doc:', docId);
        } else {
          console.log('Mapping owner mismatch, not deleting:', docId, 'owner=', owner, 'user=', userDocRef.id);
        }
      } catch (e) {
        console.error('Error deleting mapping doc', docId, e);
      }
    };
    await tryDelete(slug);
    await tryDelete(pageId);

    // optional: clear pending-payments
    try {
      const pendingRef = dbInstance.collection('pending-payments');
      const q = await pendingRef.where('userId','==',userDocRef.id).limit(100).get();
      if (!q.empty) {
        const batch = dbInstance.batch();
        q.docs.forEach(d => batch.delete(d.ref));
        await batch.commit();
        console.log('Deleted pending-payments for user:', userDocRef.id);
      }
    } catch (e) {
      console.error('Failed deleting pending-payments (non-fatal):', e);
    }

    // log cleanup
    try {
      await dbInstance.collection('paystack-cleanups').add({
        userRef: userDocRef.path,
        slug: slug || null,
        pageId: pageId || null,
        reference: reference || null,
        email: email || null,
        cleanedAt: admin.firestore.FieldValue.serverTimestamp(),
      });
    } catch (e) {
      console.error('Failed logging cleanup:', e);
    }
  } catch (e) {
    console.error('Unexpected cleanup error:', 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.');

  // audit write
  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);
    // payload.data is the object of interest
    const data = payload.data || {};

    // Extract slug candidate:
    // prefer: data.page.id / data.page.slug / data.slug
    // else: look into data.metadata.referrer URL and extract /pay/<slug>
    let maybePageId = data.page?.id || data.page_id || null;
    let maybeSlug = data.page?.slug || data.slug || null;

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

    // Also log the metadata object for debugging
    console.log('payload.data.metadata (raw):', data.metadata);

    // Try to extract userId from other places (metadata.custom_fields, customer.metadata, email)
    let metadataUserId = null;
    let customerEmail = null;
    let extractorSource = null;
    try {
      // quick extraction: metadata.userId etc
      const metadata = data.metadata || {};
      if (metadata.userId || metadata.user_id) {
        metadataUserId = metadata.userId || metadata.user_id;
        extractorSource = 'metadata';
      } else if (data.customer?.metadata) {
        const cm = data.customer.metadata;
        if (cm.userId || cm.user_id) {
          metadataUserId = cm.userId || cm.user_id;
          extractorSource = 'customer.metadata';
        }
      } 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;
            extractorSource = 'custom_fields';
            break;
          }
        }
      }
    } catch (e) {
      console.error('Error during quick metadata extraction:', e);
    }

    if (!customerEmail && data.customer?.email) customerEmail = data.customer.email;
    const paystackCustomerId = data.customer?.id ?? data.customer?.customer_code ?? null;

    // Resolve user: mapping-first using maybeSlug (important)
    let userDocRef = null;
    try {
      const mappingKey = maybeSlug || maybePageId || metadataUserId || null;
      if (mappingKey && db) {
        userDocRef = await resolveUserDocFromMapping(db, mappingKey);
        if (userDocRef) console.log('resolveUserDocFromMapping found user:', userDocRef.path, 'using key:', mappingKey);
        else console.log('resolveUserDocFromMapping found nothing for key:', mappingKey);
      }
      if (!userDocRef) {
        userDocRef = await findUserDocRef(db, { metadataUserId, email: customerEmail, paystackCustomerId });
        if (userDocRef) console.log('findUserDocRef found user:', userDocRef.path);
      }
    } catch (e) {
      console.error('Error resolving userDocRef (mapping-first):', e);
      userDocRef = null;
    }

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

      if (userDocRef && subscriptionCode) {
        try {
          const updateObj = {
            subscriptionId: subscriptionCode,
            subscription: {
              id: subscriptionCode,
              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 (paystackCustomerIdLocal) updateObj.paystack_customer_id = String(paystackCustomerIdLocal);
          await userDocRef.update(updateObj);
          console.log('subscription.create: updated user with subscription:', subscriptionCode);
        } catch (e) {
          console.error('subscription.create: failed to update user:', e);
        }
      } else {
        console.warn('subscription.create received but user not found or subscriptionCode missing — skipping user update.');
      }
    }

    // charge.success handler - entitlement add
    if (isPayment) {
      console.log('charge.success identifiers:', { metadataUserId, customerEmail, maybeSlug, maybePageId, paystackCustomerId, extractorSource });

      const recurringMarker = Boolean((data.metadata && (data.metadata.custom_filters?.recurring || data.metadata.recurring)) || false);
      const hasSubscription = !!(data.subscription || data.subscriptions || data.plan);
      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(),
      };

      // debug record
      try {
        if (db) {
          await db.collection('paystack-debug').add({
            kind: 'charge-success',
            mappingKey: maybeSlug || maybePageId || null,
            identifiers: { metadataUserId, customerEmail, maybeSlug, maybePageId, paystackCustomerId, extractorSource },
            entitlement,
            raw: data,
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
          });
        }
      } catch (e) {
        console.error('Failed writing paystack-debug:', e);
      }

      if (userDocRef && isLikelySubscriptionPayment) {
        try {
          console.log('Adding entitlement to', userDocRef.path);
          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);
          // fallback: read-modify-write
          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);
            try {
              if (db) {
                await db.collection('paystack-debug-failures').add({
                  kind: 'entitlement-persist-failure',
                  userRef: userDocRef.path,
                  error: String(err2 && err2.message ? err2.message : err2),
                  entitlement,
                  raw: data,
                  createdAt: admin.firestore.FieldValue.serverTimestamp(),
                });
              }
            } catch (e) {
              console.error('Failed writing failure debug doc:', e);
            }
          }
        }

        // cleanup (best effort)
        try {
          await cleanUpAfterSuccessfulCharge(db, userDocRef, { slug: maybeSlug, pageId: maybePageId, reference: entitlement.reference || entitlement.id, email: customerEmail });
        } catch (e) {
          console.error('Cleanup 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.');
        try {
          if (db) {
            await db.collection('paystack-unmatched').add({
              kind: 'charge.success.unmatched',
              mappingKey: maybeSlug || maybePageId || null,
              identifiers: { metadataUserId, customerEmail, maybeSlug, maybePageId, paystackCustomerId, extractorSource },
              raw: data,
              createdAt: admin.firestore.FieldValue.serverTimestamp(),
            });
          }
        } catch (e) { console.error('Failed creating unmatched debug doc:', e); }
      }
    }

    // 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);
          } 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 -------------------- */

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 docs: docId = slug and docId = pageId if available
    try {
      if (db) {
        const slug = pageData.slug || pageData.data?.slug || null;
        const pageId = pageData.id || pageData.data?.id || null;

        if (slug) {
          await db.collection('paystack-page-mappings').doc(String(slug)).set({
            userId: String(userId),
            userIdType: String(userId).includes('@') ? 'email' : 'uid',
            pageId: pageId ? String(pageId) : null,
            slug: String(slug),
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
          }, { merge: true });
          console.log('Saved page slug mapping for', slug);
        }

        if (pageId) {
          await db.collection('paystack-page-mappings').doc(String(pageId)).set({
            userId: String(userId),
            userIdType: String(userId).includes('@') ? 'email' : 'uid',
            pageId: String(pageId),
            slug: slug || null,
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
          }, { merge: true });
          console.log('Saved pageId mapping for', pageId);
        }
      }
    } catch (e) {
      console.error('Failed to persist mapping docs:', 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.json({ ok: true }));

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).');
});