const router = require('express').Router();
const fetch  = require('node-fetch');
const db     = require('../lib/db');
const { processWebhookEvent } = require('../lib/bot');

const APP_ID     = process.env.IG_APP_ID;
const APP_SECRET = process.env.IG_APP_SECRET;
const REDIRECT   = process.env.IG_REDIRECT || 'https://vianexu.com/ig/callback';
const SCOPES     = 'instagram_business_basic,instagram_business_content_publish,instagram_business_manage_comments,instagram_business_manage_messages,instagram_business_manage_insights';

// ── Start OAuth ───────────────────────────────────────────────────────────────
router.get('/connect', (req, res) => {
  if (!req.session.userId) return res.redirect('/en/login');
  const state = Math.random().toString(36).slice(2) + Date.now().toString(36);
  // Salva state no banco — robusto contra múltiplos processos no Namecheap
  db.prepare('UPDATE users SET ig_state=? WHERE id=?').run(state, req.session.userId);
  const url = `https://www.instagram.com/oauth/authorize?` + new URLSearchParams({
    client_id: APP_ID, redirect_uri: REDIRECT,
    scope: SCOPES, response_type: 'code', state
  });
  res.redirect(url);
});

// ── OAuth callback ────────────────────────────────────────────────────────────
router.get('/callback', async (req, res) => {
  const fs = require('fs'), path = require('path');
  const dbg = { userId: req.session.userId, queryState: req.query.state, code: !!req.query.code, error: req.query.error };
  fs.appendFileSync(path.join(__dirname, '../data/oauth.log'), JSON.stringify(dbg) + '\n');
  if (!req.session.userId)              return res.redirect('/en/login');
  const userForState = db.prepare('SELECT ig_state FROM users WHERE id=?').get(req.session.userId);
  if (!userForState || req.query.state !== userForState.ig_state) {
    console.log('[ig/callback] STATE MISMATCH — db:', userForState?.ig_state, 'query:', req.query.state);
    req.flash('error', 'Invalid OAuth state.'); return res.redirect('/en/dashboard/instagram');
  }
  if (!req.query.code) {
    req.flash('error', 'Authorization cancelled.'); return res.redirect('/en/dashboard/instagram');
  }

  try {
    // Exchange code → token
    const tokenRes = await fetch('https://api.instagram.com/oauth/access_token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        client_id: APP_ID, client_secret: APP_SECRET,
        grant_type: 'authorization_code',
        redirect_uri: REDIRECT, code: req.query.code
      })
    });
    const tokenData = await tokenRes.json();
    console.log('[ig/callback] tokenData:', JSON.stringify(tokenData));
    if (!tokenData.access_token) throw new Error(tokenData.error_message || JSON.stringify(tokenData));

    const shortToken = tokenData.access_token;

    // Exchange short-lived token → long-lived token (~60 days)
    const llRes = await fetch(
      `https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=${APP_SECRET}&access_token=${shortToken}`
    );
    const llData = await llRes.json();
    console.log('[ig/callback] long-lived token exchange:', JSON.stringify(llData));
    const token = llData.access_token || shortToken; // fallback to short if exchange fails

    // Get id + username as strings (avoids JS float precision loss on large user_id numbers)
    const meRes  = await fetch(`https://graph.instagram.com/v21.0/me?fields=id,username,name&access_token=${token}`);
    const me     = await meRes.json();
    console.log('[ig/callback] me:', JSON.stringify(me));
    const igUid  = me.id; // string — safe from precision loss
    const username = me.username || me.name || igUid;

    db.prepare('UPDATE users SET ig_user_id=?,ig_token=?,ig_username=? WHERE id=?').run(igUid, token, username, req.session.userId);

    // Ativa webhook subscription para esta conta (messages + comments)
    try {
      await fetch(`https://graph.instagram.com/v21.0/${igUid}/subscribed_apps`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          subscribed_fields: 'messages,comments,live_comments,message_reactions,messaging_seen',
          access_token: token
        })
      });
    } catch (e) {
      console.error('[ig/callback] webhook subscription error:', e.message);
    }

    req.flash('success', `Instagram @${username} connected!`);
    res.redirect('/en/dashboard/instagram');
  } catch (e) {
    req.flash('error', 'OAuth error: ' + e.message);
    res.redirect('/en/dashboard/instagram');
  }
});

// ── Refresh long-lived token ──────────────────────────────────────────────────
router.get('/refresh', async (req, res) => {
  if (!req.session.userId) return res.redirect('/en/login');
  const user = db.prepare('SELECT * FROM users WHERE id=?').get(req.session.userId);
  if (!user || !user.ig_token) { req.flash('error', 'No token to refresh.'); return res.redirect('/en/dashboard/instagram'); }
  try {
    const r = await fetch(`https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=${user.ig_token}`);
    const d = await r.json();
    if (!d.access_token) throw new Error(JSON.stringify(d));
    db.prepare('UPDATE users SET ig_token=? WHERE id=?').run(d.access_token, user.id);
    req.flash('success', 'Instagram token refreshed.');
  } catch(e) {
    req.flash('error', 'Refresh failed: ' + e.message);
  }
  res.redirect('/en/dashboard/instagram');
});

// ── Webhook (bot multi-tenant) ────────────────────────────────────────────────
const WEBHOOK_VERIFY_TOKEN = process.env.IG_WEBHOOK_VERIFY_TOKEN || 'vianexu_webhook_token';

router.get('/webhook', (req, res) => {
  const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;
  if (mode === 'subscribe' && token === WEBHOOK_VERIFY_TOKEN) return res.status(200).send(challenge);
  res.sendStatus(403);
});

router.post('/webhook', (req, res) => {
  res.sendStatus(200);
  const fs  = require('fs');
  const log = JSON.stringify({ ts: new Date().toISOString(), body: req.body }) + '\n';
  fs.appendFileSync(require('path').join(__dirname, '../data/webhook.log'), log);
  processWebhookEvent(req.body).catch(e => console.error('[webhook] erro:', e.message));
});

// ── Deauthorize (Meta required) ───────────────────────────────────────────────
router.post('/deauth', (req, res) => {
  try {
    const payload = JSON.parse(Buffer.from((req.body.signed_request || '').split('.')[1], 'base64').toString());
    if (payload.user_id) db.prepare('UPDATE users SET ig_token=NULL,ig_user_id=NULL,ig_username=NULL WHERE ig_user_id=?').run(payload.user_id);
  } catch {}
  res.json({ success: true });
});

// ── Data deletion (Meta required) ─────────────────────────────────────────────
router.post('/delete-data', (req, res) => {
  const conf = 'DEL_' + Date.now().toString(36).toUpperCase();
  try {
    const payload = JSON.parse(Buffer.from((req.body.signed_request || '').split('.')[1], 'base64').toString());
    if (payload.user_id) db.prepare('DELETE FROM users WHERE ig_user_id=?').run(payload.user_id);
  } catch {}
  res.json({ url: `https://vianexu.com/ig/delete-status?id=${conf}`, confirmation: conf });
});

router.get('/delete-status', (req, res) => {
  res.send(`<p style="font-family:sans-serif;padding:40px">Data deleted. Confirmation: <b>${req.query.id || ''}</b></p>`);
});

module.exports = router;
