File size: 27,325 Bytes
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a16c6f
 
36d488d
7a16c6f
 
36d488d
 
 
7a16c6f
36d488d
 
 
 
 
 
c5e36fc
 
 
 
 
36d488d
59ea1b6
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59ea1b6
 
 
 
 
 
 
 
 
 
 
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baba0aa
 
 
 
 
 
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0227230
 
 
36d488d
 
0227230
36d488d
0227230
2295c9c
 
0227230
 
2295c9c
 
 
 
 
 
 
 
 
7921eac
36d488d
 
 
7921eac
36d488d
 
 
 
 
 
 
 
0acfe9d
 
 
 
 
 
 
 
 
 
 
 
 
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28f892f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36d488d
 
 
28f892f
7e6933d
28f892f
7e6933d
28f892f
7e6933d
 
 
 
 
 
 
28f892f
 
 
 
 
7e6933d
 
4fc4e21
7e6933d
28f892f
 
 
 
36d488d
 
 
 
 
 
 
 
 
e8f6f7b
 
428e88d
 
7e6933d
428e88d
36d488d
7e6933d
 
092070c
91ff24f
e8f6f7b
 
7e6933d
e8f6f7b
36d488d
092070c
7e6933d
 
 
 
092070c
 
 
7e6933d
092070c
 
 
 
 
 
 
 
 
7e6933d
 
092070c
 
7e6933d
092070c
36d488d
092070c
 
e8f6f7b
7e6933d
092070c
36d488d
7e6933d
36d488d
 
 
 
 
 
91ff24f
 
 
 
 
 
 
 
 
 
36d488d
91ff24f
cd4f86d
 
91ff24f
 
36d488d
 
91ff24f
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91ff24f
 
 
 
36d488d
 
 
 
91ff24f
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8f6f7b
092070c
e8f6f7b
092070c
129ae24
 
7c32afc
092070c
e8f6f7b
 
092070c
e8f6f7b
 
 
 
 
 
36d488d
 
e8f6f7b
 
36d488d
 
 
e8f6f7b
36d488d
e8f6f7b
36d488d
 
 
b671c20
 
e8f6f7b
b671c20
 
36d488d
 
 
 
 
e8f6f7b
 
 
b671c20
 
 
3cfcb2e
 
b671c20
 
 
3cfcb2e
 
df9cf4e
b671c20
 
3cfcb2e
 
e8f6f7b
36d488d
 
 
 
 
 
 
 
9229566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d95d18
2cb7484
 
 
 
 
0d95d18
 
 
 
 
 
 
 
 
 
 
 
0acfe9d
 
 
 
2cb7484
 
 
 
0d95d18
2cb7484
36d488d
 
 
 
 
ede1a98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const { google } = require('googleapis');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('./utils/db');
require('dotenv').config();
global.crypto = require('crypto');

const rateLimit = require('express-rate-limit');

const app = express();
app.set('trust proxy', 1); // Fix for Hugging Face/Proxy Rate Limiting

// Global Rate Limiter (DISABLED for troubleshooting)
/*
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, 
  max: 100, 
  message: { error: 'Too many requests, please try again later.' }
});
app.use(limiter);
*/

const PORT = process.env.PORT || 7860;
const JWT_SECRET = process.env.JWT_SECRET || 'youtube-automation-super-secret-2026';

app.use(express.json());
app.use(express.static(path.join(__dirname, 'dashboard')));
app.use('/video', express.static(path.join(__dirname, 'video'), {
  setHeaders: (res, path) => {
    if (path.endsWith('.mp4')) res.set('Content-Type', 'video/mp4');
  }
}));

// JWT Middleware
// Admin Authentication Middleware
const authenticateAdmin = (req, res, next) => {
  authenticateToken(req, res, async () => {
    try {
      const { data: user, error } = await db.from('users').select('email, role').eq('id', req.userId).single();
      console.log(`🔑 Security Check: User ${user?.email} is [${user?.role || 'user'}]`);
      
      if (user && user.role === 'admin') {
        console.log("✅ Admin Access Authorized");
        next();
      } else {
        console.warn(`❌ Unauthorized Admin Attempt: ${user?.email}`);
        res.status(403).json({ error: 'Access Denied: Admin Role Required' });
      }
    } catch (e) {
      console.error("🔥 Auth System Error:", e);
      res.status(500).json({ error: 'Security Engine Error' });
    }
  });
};

const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) return res.status(401).json({ error: 'Please login' });

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) return res.status(403).json({ error: 'Session expired' });
    req.userId = user.id;
    next();
  });
};

// --- OAuth2 Configuration ---
async function getOAuth2Client(customClientId = null, customClientSecret = null) {
  try {
    if (!customClientId || !customClientSecret) {
      return null; 
    }

    const client_id = customClientId;
    const client_secret = customClientSecret;

    const redirectUri = (process.env.SPACE_ID || process.env.NODE_ENV === 'production') 
      ? 'https://yogesh7705-youtube-auto-bot.hf.space/api/auth/callback' 
      : 'http://localhost:7860/api/auth/callback';
      
    return new google.auth.OAuth2(client_id, client_secret, redirectUri);
  } catch (e) {
    console.error('❌ OAuth Client Error:', e.message);
    return null;
  }
}

// --- Auth API ---

app.get('/api/config', (req, res) => {
  res.json({
    supabaseUrl: process.env.SUPABASE_URL,
    supabaseKey: process.env.SUPABASE_ANON_KEY
  });
});

app.post('/api/auth/signup', async (req, res) => {
  const { email, password } = req.body;
  console.log(`🚀 [Signup Start] Attempting for: ${email}`);
  
  try {
    // 1. Check Global Capacity
    const { count: totalUsers } = await db.from('users').select('*', { count: 'exact', head: true });
    console.log(`📊 [Signup] Current users: ${totalUsers}/100`);
    if (totalUsers >= 100) return res.status(403).json({ error: 'Platform at 100-user capacity.' });

    // 2. Hash Password
    const hashedPassword = await bcrypt.hash(password, 10);
    console.log(`🔐 [Signup] Password hashed.`);

    // 3. Create User
    const { data: users, error: userError } = await db.from('users').insert([
      { email, password: hashedPassword, role: 'user', plan: 'free' }
    ]).select();
    
    if (userError) {
      console.error("❌ [Signup] DB Error:", userError.message);
      return res.status(400).json({ error: userError.message });
    }

    const newUser = users[0];
    console.log(`✅ [Signup] User created with ID: ${newUser.id}`);

    // 4. Initialize Channel (Non-blocking)
    try {
      await db.from('channels').insert([{
        user_id: newUser.id,
        is_active: false,
        niche: 'Facts',
        preferred_hours: ['10:00']
      }]);
      console.log(`📺 [Signup] Channel row initialized.`);
    } catch (chanErr) {
      console.warn("⚠️ [Signup] Channel init skipped:", chanErr.message);
    }

    const token = jwt.sign({ id: newUser.id }, JWT_SECRET, { expiresIn: '30d' });
    res.json({ success: true, token });
  } catch (e) {
    console.error("🔥 [Signup] Critical Crash:", e.message);
    res.status(500).json({ error: 'Internal Security Engine Error' });
  }
});

app.post('/api/auth/login', async (req, res) => {
  const emailInput = (req.body.email || "").trim();
  const password = req.body.password;
  console.log(`🔑 [Login Start] Attempting for: ${emailInput}`);
  
  try {
    const { data: user, error } = await db.from('users').select('*').ilike('email', emailInput).single();
    
    if (error) {
      console.error(`❌ [Login DB Error] ${error.message} for ${emailInput}`);
      return res.status(401).json({ error: `Database Error: ${error.message}` });
    }

    if (!user) {
      console.warn(`❌ [Login Failed] User not found: ${emailInput}`);
      return res.status(401).json({ error: 'User account not found' });
    }

    const isMatch = await bcrypt.compare(password, user.password);
    console.log(`🔐 [Login Debug] Password match for ${emailInput}: ${isMatch}`);

    if (isMatch) {
      console.log(`✅ [Login Success] ${emailInput}`);
      const token = jwt.sign({ id: user.id }, JWT_SECRET, { expiresIn: '30d' });
      res.json({ success: true, token });
    } else {
      console.warn(`❌ [Login Failed] Invalid credentials for: ${emailInput}`);
      res.status(401).json({ error: 'Invalid email or password' });
    }
  } catch (e) {
    console.error("🔥 [Login Crash]:", e.message);
    res.status(500).json({ error: 'Authentication engine error' });
  }
});

app.post('/api/test-db', authenticateToken, async (req, res) => {
  try {
    const { error } = await db.from('activity').insert([{
      user_id: req.userId,
      type: 'LOG',
      message: '🧪 Database Connection Test Successful!'
    }]);
    if (error) throw error;
    res.json({ success: true });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

app.get('/api/auth/me', authenticateToken, async (req, res) => {
  try {
    let { data: user } = await db.from('users').select('email, role, plan, plan_expires_at').eq('id', req.userId).single();
    
    // 🛡️ SUBSCRIPTION GUARD: Check for Expiry
    if (user?.plan === 'premium' && user.plan_expires_at) {
      if (new Date(user.plan_expires_at) < new Date()) {
        console.log(`📉 Plan Expired for ${user.email}. Reverting to free.`);
        await db.from('users').update({ plan: 'free' }).eq('id', req.userId);
        user.plan = 'free';
      }
    }

    // MIRROR DB: Return plan exactly as stored in Database
    let finalPlan = user?.plan || 'free';
    
    res.json({ 
      loggedIn: true, 
      email: user?.email, 
      role: user?.role, 
      plan: finalPlan,
      expires_at: user?.plan_expires_at 
    });
  } catch (e) {
    res.json({ loggedIn: false });
  }
});

// --- Platform Pricing ---
app.get('/api/platform/pricing', async (req, res) => {
  const { data } = await db.from('platform_settings').select('value').eq('key', 'pricing').single();
  res.json(data?.value || {});
});

app.post('/api/admin/pricing', authenticateAdmin, async (req, res) => {
  try {
    const { pricing } = req.body;
    if (!pricing) return res.status(400).json({ error: "Missing pricing data" });

    console.log("💾 [Admin] Attempting to Save Pricing:", JSON.stringify(pricing));
    
    // Use upsert to update the 'pricing' row specifically
    const { error } = await db.from('platform_settings')
        .upsert({ key: 'pricing', value: pricing }, { onConflict: 'key' });
    
    if (error) {
      console.error("🔥 [DB Error] Pricing Save Failed:", error.message, error.details);
      return res.status(500).json({ error: error.message });
    }
    
    console.log("✅ [Admin] Pricing Engine Synced Successfully.");
    res.json({ success: true });
  } catch (e) {
    console.error("🔥 [API Crash] Pricing Save Engine:", e.message);
    res.status(500).json({ error: e.message });
  }
});

// --- Razorpay Payments ---
const Razorpay = require('razorpay');
let rzp;

if (process.env.RAZORPAY_KEY_ID) {
  rzp = new Razorpay({
    key_id: process.env.RAZORPAY_KEY_ID,
    key_secret: process.env.RAZORPAY_KEY_SECRET
  });
  console.log("💳 Razorpay Revenue Engine: ONLINE");
} else {
  console.warn("⚠️ Razorpay Keys missing. Payments are currently disabled.");
}

app.post('/api/payments/create-order', authenticateToken, async (req, res) => {
  const { plan } = req.body;
  
  // 1. Fetch Dynamic Pricing from Settings
  const { data: settings } = await db.from('platform_settings').select('value').eq('key', 'pricing').single();
  const p = settings?.value || { pro_monthly: 299, pro_yearly: 2999, discount_active: false };
  
  // 2. Determine Base Price
  let amount = plan === 'pro_yearly' ? p.pro_yearly : p.pro_monthly;
  
  // 3. Apply Discount based on specific plan toggle
  const isMonthlySale = plan === 'pro_monthly' && p.m_discount_active;
  const isYearlySale = plan === 'pro_yearly' && p.y_discount_active;

  if ((isMonthlySale || isYearlySale) && p.discount_percent > 0) {
    amount = Math.round(amount * (1 - p.discount_percent / 100));
  }

  const options = {
    amount: amount * 100, // Razorpay uses paise
    currency: "INR",
    receipt: `receipt_${Date.now()}`
  };

  try {
    const order = await rzp.orders.create(options);
    res.json(order);
  } catch (e) {
    console.error("Razorpay Error:", e);
    res.status(500).send(e.message);
  }
});

app.post('/api/payments/verify', authenticateToken, async (req, res) => {
  try {
    const { razorpay_order_id, razorpay_payment_id, plan_type } = req.body;
    
    // 1. Get current expiry
    const { data: user } = await db.from('users').select('plan_expires_at').eq('id', req.userId).single();
    
    // 2. Calculate New Expiry (Stackable)
    const days = plan_type === 'pro_yearly' ? 365 : 30;
    let baseDate = new Date();
    
    // If user already has an active plan, add to it!
    if (user?.plan_expires_at && new Date(user.plan_expires_at) > new Date()) {
        baseDate = new Date(user.plan_expires_at);
    }
    
    baseDate.setDate(baseDate.getDate() + days);

    await db.from('users').update({ 
      plan: 'premium',
      plan_expires_at: baseDate.toISOString()
    }).eq('id', req.userId);
    
    res.json({ success: true });
  } catch (e) {
    res.status(500).json({ error: 'Verification failed' });
  }
});

// --- Admin Control API ---
app.get('/api/admin/users', authenticateAdmin, async (req, res) => {
  try {
    const { data: users, error } = await db.from('users').select('id, email, plan, role, created_at').order('created_at', { ascending: false });
    if (error) throw error;
    res.json(users);
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

app.post('/api/admin/update-plan', authenticateAdmin, async (req, res) => {
  const { userId, plan } = req.body;
  try {
    const { error } = await db.from('users').update({ plan }).eq('id', userId);
    if (error) throw error;
    res.json({ success: true, msg: `User updated to ${plan}` });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

// --- Dashboard API ---

app.get('/api/stats', authenticateToken, async (req, res) => {
  try {
    // 1. Fetch channel data (niche, stats) - Prioritize active channels
    const { data: channel } = await db.from('channels')
      .select('niche, preferred_hours, total_views, subscribers')
      .eq('user_id', req.userId)
      .order('is_active', { ascending: false }) 
      .limit(1).maybeSingle();
    
    // 2. Fetch user data (custom keys)
    const { data: user } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', req.userId).single();
    
    const { count: videosProduced } = await db.from('activity').select('*', { count: 'exact', head: true }).eq('user_id', req.userId).eq('type', 'VIDEO_PUBLISHED');
    
    res.json({
      videosProduced: videosProduced || 0,
      totalViews: channel?.total_views || 0,
      subscribers: channel?.subscribers || 0,
      niche: channel ? channel.niche : 'Not set',
      preferred_hours: channel ? channel.preferred_hours : ['10:00'],
      custom_client_id: user?.custom_client_id || '',
      custom_client_secret: user?.custom_client_secret || ''
    });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

app.get('/api/youtube/status', authenticateToken, async (req, res) => {
  const { data } = await db.from('channels').select('token').eq('user_id', req.userId).single();
  res.json({ connected: !!data?.token });
});

app.get('/api/youtube', authenticateToken, async (req, res) => {
  try {
    const { data: channels, error: chanError } = await db.from('channels').select('token, channel_id, channel_name, total_views, subscribers').eq('user_id', req.userId);
    if (chanError) throw chanError;

    if (!channels || channels.length === 0) {
        return res.json({ connected: false, channels: [] });
    }

    const { data: user } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', req.userId).single();
    
    const results = [];
    const oauth2Client = await getOAuth2Client(user?.custom_client_id, user?.custom_client_secret);
    
    if (!oauth2Client) {
        return res.json({ connected: false, channels: channels.map(c => ({ ...c, connected: false })) });
    }

    for (const chan of channels) {
      if (!chan.token || !chan.channel_id) {
          results.push({ ...chan, connected: false });
          continue;
      }
      try {
        oauth2Client.setCredentials(chan.token);
        const youtube = google.youtube({ version: 'v3', auth: oauth2Client });
        const response = await youtube.channels.list({ part: 'statistics', id: chan.channel_id });
        if (response.data.items && response.data.items.length > 0) {
          const stats = response.data.items[0].statistics;
          results.push({
            connected: true,
            channel_id: chan.channel_id,
            channel_name: chan.channel_name,
            subscribers: parseInt(stats.subscriberCount),
            totalViews: parseInt(stats.viewCount)
          });
        } else {
            results.push({ ...chan, connected: false });
        }
      } catch (e) {
        results.push({ ...chan, connected: false });
      }
    }

    res.json({ 
      connected: results.some(r => r.connected), 
      channels: results 
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.post('/api/settings', authenticateToken, async (req, res) => {
  const { niche, preferred_hours, custom_client_id, custom_client_secret } = req.body;
  try {
    // 1. Update YouTube Credentials in USERS table
    const { error: userError } = await db.from('users').update({ 
      custom_client_id, 
      custom_client_secret 
    }).eq('id', req.userId);

    if (userError) throw userError;

    // 2. Update Production Settings in ALL CHANNELS for this user
    const { error: chanError } = await db.from('channels').update({ 
      niche, 
      preferred_hours
    }).eq('user_id', req.userId);

    if (chanError) throw chanError;

    res.json({ success: true });
  } catch (e) {
    console.error('❌ Settings Save Error:', e);
    res.status(500).json({ error: 'Failed to save settings' });
  }
});

app.post('/api/youtube/disconnect', authenticateToken, async (req, res) => {
  try {
    await db.from('channels').update({ 
      token: null, 
      is_active: false,
      channel_id: null,
      channel_name: null 
    }).eq('user_id', req.userId);
    res.json({ success: true });
  } catch (e) {
    res.status(500).json({ error: 'Failed to disconnect' });
  }
});

app.get('/api/auth/url', authenticateToken, async (req, res) => {
  // Fetch keys from Users table
  const { data: user } = await db.from('users').select('custom_client_id, custom_client_secret').eq('id', req.userId).single();
  
  const oauth2Client = await getOAuth2Client(user?.custom_client_id, user?.custom_client_secret);
  if (!oauth2Client) return res.status(500).json({ error: 'OAuth Client not configured' });

  const state = Buffer.from(JSON.stringify({ 
    userId: req.userId,
    custom_client_id: user?.custom_client_id,
    custom_client_secret: user?.custom_client_secret
  })).toString('base64');

  const authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: ['https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/youtube.upload'],
    prompt: 'consent',
    state: state
  });
  res.json({ url: authUrl });
});

app.get('/api/auth/callback', async (req, res) => {
  const { code, state } = req.query;
  const decoded = JSON.parse(Buffer.from(state, 'base64').toString());
  const userId = decoded.userId;
  
  const oauth2Client = await getOAuth2Client(decoded.custom_client_id, decoded.custom_client_secret);
  if (!oauth2Client) return res.status(500).send('OAuth Client Configuration Error');

  try {
    const { tokens } = await oauth2Client.getToken(code);
    oauth2Client.setCredentials(tokens);
    const youtube = google.youtube({ version: 'v3', auth: oauth2Client });
    const chanRes = await youtube.channels.list({ part: 'snippet', mine: true });
    
    if (chanRes.data.items && chanRes.data.items.length > 0) {
      const channel = chanRes.data.items[0];
      
      // 1. Check if Channel is BLACKLISTED
      const { data: isBanned } = await db.from('blacklist').select('channel_id').eq('channel_id', channel.id).single();
      if (isBanned) {
        return res.send('<h1>🚫 Channel Banned</h1><p>This YouTube channel has been permanently blacklisted from ViralFlow AI.</p>');
      }

      // 4. Multi-Channel Logic
      const { data: user } = await db.from('users').select('plan, role').eq('id', userId).single();
      const { data: existingChannels, count: currentChannels } = await db.from('channels').select('*', { count: 'exact' }).eq('user_id', userId);
      
      const isAdmin = user?.role === 'admin' || user?.plan === 'ultra';
      const isPremium = user?.plan === 'premium';
      const limit = isAdmin ? 999 : (isPremium ? 2 : 1); 

      // 5. Check if this specific channel is already connected to this user
      const hasThisChannel = existingChannels?.find(c => c.channel_id === channel.id);

      if (!hasThisChannel && (currentChannels || 0) >= limit) {
        // SPECIAL CASE: If they have a "placeholder" channel (no channel_id), we can replace it!
        const placeholder = existingChannels?.find(c => !c.channel_id);
        if (!placeholder) {
          return res.send(`<h1>❌ Limit Reached</h1><p>Your ${user?.plan} plan allows only ${limit} channel(s). Upgrade to add more.</p>`);
        }
      }

      // 6. Check if this channel is already connected to another user
      const { data: otherUserChannel } = await db.from('channels')
        .select('user_id')
        .eq('channel_id', channel.id)
        .neq('user_id', userId)
        .maybeSingle();

      if (otherUserChannel) {
        return res.send('<h1>❌ Connection Denied</h1><p>This YouTube channel is already linked to another account.</p>');
      }

      // 7. FINAL LINKING LOGIC (Universal)
      const existingChannel = existingChannels?.find(c => c.channel_id === channel.id);
      const placeholder = existingChannels?.find(c => !c.channel_id);

      const channelData = {
        user_id: userId,
        channel_id: channel.id,
        channel_name: channel.snippet.title,
        token: tokens,
        is_active: true,
        is_locked: true
      };

      if (existingChannel) {
        // Case A: Update existing connection
        console.log(`♻️ Updating existing channel: ${channel.id}`);
        const { error } = await db.from('channels').update(channelData).eq('id', existingChannel.id);
        if (error) throw error;
      } else if (placeholder) {
        // Case B: Fill the first empty slot
        console.log(`📥 Filling placeholder slot: ${placeholder.id}`);
        const { error } = await db.from('channels').update(channelData).eq('id', placeholder.id);
        if (error) throw error;
      } else {
        // Case C: Create a brand new slot (for 2nd, 3rd channels etc)
        console.log(`➕ Creating new channel slot for: ${channel.id}`);
        const { error } = await db.from('channels').insert([channelData]);
        if (error) throw error;
      }
    }
    res.send('<h1>✅ YouTube Connected!</h1><p>Close this and refresh your dashboard.</p>');
  } catch (e) {
    res.status(500).send('Auth Error: ' + e.message);
  }
});

app.post('/api/generate', authenticateToken, async (req, res) => {
  try {
    const { data: channels } = await db.from('channels').select('*').eq('user_id', req.userId).eq('is_active', true);
    if (channels && channels.some(c => c.is_processing)) {
      return res.status(400).json({ error: 'Production already in progress. Please wait or Reset Lock.' });
    }
    const { runDailyAutomation } = require('./utils/autonomous-agent');
    runDailyAutomation(req.userId).catch(console.error);
    res.json({ message: 'Started!' });
  } catch (e) {
    res.status(500).json({ error: 'Production Engine Error' });
  }
});

app.post('/api/generate/reset', authenticateToken, async (req, res) => {
  try {
    await db.from('channels').update({ is_processing: false }).eq('user_id', req.userId);
    await db.from('activity').insert([{ user_id: req.userId, type: 'LOG', message: '♻️ User manually reset production lock.' }]);
    res.json({ message: 'Lock Cleared! You can now start a new production.' });
  } catch (e) {
    res.status(500).json({ error: 'Reset Failed' });
  }
});

app.get('/api/admin/global-stats', authenticateAdmin, async (req, res) => {
  try {
    const { count: totalUsers } = await db.from('users').select('*', { count: 'exact', head: true });
    const { count: activeChannels } = await db.from('channels').select('*', { count: 'exact', head: true }).eq('is_active', true);
    const { count: totalVideos } = await db.from('activity').select('*', { count: 'exact', head: true }).eq('type', 'VIDEO_PUBLISHED');
    
    res.json({ totalUsers, activeChannels, totalVideos });
  } catch (e) {
    res.status(500).json({ error: 'Failed to fetch global stats' });
  }
});

app.post('/api/admin/remove-channel', authenticateAdmin, async (req, res) => {
  const { targetUserId, action } = req.body; // action: 'release' or 'ban'
  
  try {
    const { data: channel } = await db.from('channels').select('channel_id').eq('user_id', targetUserId).single();
    
    if (action === 'ban' && channel?.channel_id) {
      await db.from('blacklist').insert([{ channel_id: channel.channel_id, reason: 'Admin Ban' }]);
    }

    await db.from('channels').delete().eq('user_id', targetUserId);
    res.json({ success: true });
  } catch (e) {
    res.status(500).json({ error: 'Failed to execute admin action' });
  }
});

app.post('/api/admin/action', authenticateAdmin, async (req, res) => {
  try {
    const { userId, type } = req.body;
    console.log(`🛡️ [Admin] Attempting Action ${type} on User ${userId}`);

    let updateData = {};
    if (type === 'ultra') {
        updateData = { plan: 'ultra', plan_expires_at: '2099-12-31T23:59:59Z' };
    } else if (type === 'ban') {
        updateData = { role: 'banned' };
    } else if (type === 'release') {
        updateData = { role: 'user' };
    }

    const { error } = await db.from('users').update(updateData).eq('id', userId);
    
    if (error) {
        console.error(`🔥 [Admin Action Fail] ${type}:`, error.message, error.details);
        return res.status(500).json({ error: error.message });
    }

    console.log(`✅ [Admin Action Success] ${type} applied to ${userId}`);
    res.json({ success: true });
  } catch (e) {
    console.error("🔥 [API Crash] Admin Action Engine:", e.message);
    res.status(500).json({ error: e.message });
  }
});

app.get('/api/admin/users', authenticateAdmin, async (req, res) => {
  const { data: users, error } = await db.from('users')
    .select(`
      id,
      email,
      plan,
      role,
      channels (
        channel_name,
        channel_id,
        niche,
        is_active
      )
    `);
  
  if (error) return res.status(500).json({ error: error.message });
  res.json(users);
});

app.get('/api/logs', authenticateToken, async (req, res) => {
  let { data: logs, error } = await db.from('activity')
    .select('created_at, message, type, metadata')
    .eq('user_id', req.userId)
    .order('created_at', { ascending: false })
    .limit(20);
    
  // FALLBACK: If 'metadata' column is missing, try without it
  if (error && error.message.includes('metadata')) {
    console.warn("⚠️ [API/Logs] Metadata column missing, falling back...");
    const retry = await db.from('activity')
      .select('created_at, message, type')
      .eq('user_id', req.userId)
      .order('created_at', { ascending: false })
      .limit(20);
    logs = retry.data;
    error = retry.error;
  }

  if (error) {
    return res.status(500).json({ error: error.message });
  }

  res.json((logs || []).map(l => ({ 
    time: l.created_at, 
    msg: l.message, 
    type: l.type,
    metadata: l.metadata || null 
  })));
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`🚀 Permanent Memory Server running on port ${PORT}`);
});

// --- BACKGROUND SCHEDULER (Every 1 Minute) ---
setInterval(async () => {
  try {
    const now = new Date();
    // Get IST Time (matches dashboard clock)
    const istTime = now.toLocaleTimeString('en-GB', { timeZone: 'Asia/Kolkata', hour: '2-digit', minute: '2-digit' });
    
    // 1. Fetch all active channels
    const { data: channels } = await db.from('channels').select('user_id, preferred_hours, last_run').eq('is_active', true);
    
    for (const channel of channels) {
      if (channel.preferred_hours && channel.preferred_hours.includes(istTime)) {
        // 2. Prevent double-triggering within the same minute/hour
        const lastRun = channel.last_run ? new Date(channel.last_run) : new Date(0);
        const diffMinutes = (now - lastRun) / (1000 * 60);
        
        if (diffMinutes > 10) { // Only run if it hasn't run in the last 10 mins
          console.log(`⏰ [Scheduler] Triggering Production for User ${channel.user_id} at ${istTime} IST`);
          const { runDailyAutomation } = require('./utils/autonomous-agent');
          runDailyAutomation(channel.user_id).catch(err => console.error(`🔥 [Scheduler Error] User ${channel.user_id}:`, err));
        }
      }
    }
  } catch (err) {
    console.error("🔥 [Scheduler Critical Failure]:", err.message);
  }
}, 60000);