import { Router } from 'express';
import { requireAuth } from './auth.js';
import { getBotInstanceByUser, upsertBotInstance } from '../../core/db.js';
import { encryptSecret, maskSecret, decryptSecret } from '../../lib/secure.js';
import { startUserBot, stopUserBot, getUserBotStatus } from '../../core/bot-manager.js';

export const botRouter = Router();

// Semua route di sini wajib login
botRouter.use(requireAuth);

// Status bot milik user yang sedang login
botRouter.get('/status', (req, res) => {
  const status = getUserBotStatus(req.user.id);
  const inst = getBotInstanceByUser(req.user.id);
  // Jangan pernah kirim token plaintext ke client — cuma preview ter-mask
  let tokenPreview = '';
  if (inst?.token_encrypted) {
    const tok = decryptSecret(inst.token_encrypted);
    tokenPreview = maskSecret(tok);
  }
  res.json({ ...status, token_preview: tokenPreview });
});

// Simpan/ganti token bot (langsung dienkripsi sebelum masuk DB)
botRouter.post('/token', async (req, res) => {
  const { token } = req.body || {};
  if (!token || String(token).length < 50) {
    return res.status(400).json({ error: 'Token tidak valid' });
  }

  // Hentikan bot lama dulu kalau lagi jalan (token diganti)
  await stopUserBot(req.user.id).catch(() => {});

  upsertBotInstance(req.user.id, {
    token_encrypted: encryptSecret(String(token).trim()),
    status: 'stopped',
    last_error: null,
  });
  res.json({ ok: true });
});

// Start bot
botRouter.post('/start', async (req, res) => {
  const result = await startUserBot(req.user.id);
  if (!result.ok) return res.status(400).json(result);
  res.json(result);
});

// Stop bot
botRouter.post('/stop', async (req, res) => {
  const result = await stopUserBot(req.user.id);
  res.json(result);
});

// Hapus token (sekaligus stop)
botRouter.delete('/token', async (req, res) => {
  await stopUserBot(req.user.id).catch(() => {});
  upsertBotInstance(req.user.id, { token_encrypted: null, status: 'stopped', last_error: null, bot_name: null, client_id: null });
  res.json({ ok: true });
});
