const express = require('express');
const router = express.Router();
const { getDb, logAudit } = require('../db');
const emailService = require('../email');

function getActiveAccount(userId) {
  const db = getDb();
  return db.prepare('SELECT * FROM email_accounts WHERE user_id = ? AND active = 1 LIMIT 1').get(userId);
}

router.get('/', async (req, res) => {
  const db = getDb();
  const accounts = emailService.getUserAccounts(req.session.userId);
  const account = getActiveAccount(req.session.userId);
  let messages = [];
  let folders = [];
  let error = null;
  if (account) {
    try {
      messages = db.prepare('SELECT * FROM email_messages WHERE account_id = ? AND folder = ? ORDER BY date DESC LIMIT 50').all(account.id, 'INBOX');
      folders = await emailService.getMailboxes(account.id);
    } catch (e) { error = e.message; }
  }
  res.render('email-inbox', { accounts, account, messages, folders, error, user: { username: req.session.username } });
});

router.post('/sync', async (req, res) => {
  const account = getActiveAccount(req.session.userId);
  if (!account) return res.redirect('/email/settings');
  try {
    await emailService.fetchAndStoreMessages(account.id, 'INBOX', 50);
    logAudit(req.session.userId, req.session.username, 'email_sync', 'email', account.id, 'Email inbox gesynchroniseerd');
  } catch (e) { console.error('Sync error:', e.message); }
  res.redirect('/email');
});

router.get('/sync', async (req, res) => {
  const account = getActiveAccount(req.session.userId);
  if (!account) return res.json({ error: 'No account' });
  try {
    const results = await emailService.fetchAndStoreMessages(account.id, 'INBOX', 50);
    res.json({ synced: results.length });
  } catch (e) { res.json({ error: e.message }); }
});

router.get('/compose', (req, res) => {
  const accounts = emailService.getUserAccounts(req.session.userId);
  const account = getActiveAccount(req.session.userId);
  res.render('email-compose', { accounts, account, to: req.query.to || '', subject: req.query.subject || '', sent: false, error: null, user: { username: req.session.username } });
});

router.post('/compose', async (req, res) => {
  const account = getActiveAccount(req.session.userId);
  if (!account) return res.render('email-compose', { accounts: emailService.getUserAccounts(req.session.userId), account: null, to: '', subject: '', sent: false, error: 'Geen email account geconfigureerd', user: { username: req.session.username } });
  const { to, cc, bcc, subject, text, html } = req.body;
  if (!to || !subject) return res.render('email-compose', { accounts: emailService.getUserAccounts(req.session.userId), account, to, subject, sent: false, error: 'Ontvanger en onderwerp zijn verplicht', user: { username: req.session.username } });
  try {
    await emailService.sendEmail(account.id, to, subject, text, html, cc, bcc);
    logAudit(req.session.userId, req.session.username, 'email_sent', 'email', account.id, `Email naar ${to}: ${subject}`);
    res.render('email-compose', { accounts: emailService.getUserAccounts(req.session.userId), account, to: '', subject: '', sent: true, error: null, user: { username: req.session.username } });
  } catch (e) {
    res.render('email-compose', { accounts: emailService.getUserAccounts(req.session.userId), account, to, subject, sent: false, error: e.message, user: { username: req.session.username } });
  }
});

router.get('/message/:id', async (req, res) => {
  const db = getDb();
  const msg = db.prepare('SELECT * FROM email_messages WHERE id = ?').get(req.params.id);
  if (!msg) return res.redirect('/email');
  db.prepare('UPDATE email_messages SET seen = 1 WHERE id = ?').run(req.params.id);
  let fullHtml = msg.body_html;
  let fullText = msg.body_text;
  if (!fullHtml && !fullText) {
    try {
      const parsed = await emailService.getMessageBody(msg.account_id, msg.uid);
      if (parsed) {
        fullHtml = parsed.html || '';
        fullText = parsed.text || '';
        db.prepare('UPDATE email_messages SET body_text=?, body_html=? WHERE id=?').run(fullText || '', fullHtml || '', msg.id);
      }
    } catch (e) { console.error('Error fetching body:', e.message); }
  }
  msg.body_html = fullHtml;
  msg.body_text = fullText;
  res.render('email-detail', { msg, user: { username: req.session.username } });
});

router.post('/message/:id/delete', (req, res) => {
  const db = getDb();
  db.prepare('DELETE FROM email_messages WHERE id = ?').run(req.params.id);
  res.redirect('/email');
});

router.get('/settings', (req, res) => {
  const accounts = emailService.getUserAccounts(req.session.userId);
  res.render('email-settings', { accounts, error: null, saved: req.query.saved === '1', user: { username: req.session.username } });
});

router.post('/settings', (req, res) => {
  const db = getDb();
  const { email, name, imap_host, imap_port, imap_secure, imap_user, imap_pass, smtp_host, smtp_port, smtp_secure, smtp_user, smtp_pass } = req.body;
  if (!email || !imap_host || !imap_user || !imap_pass) {
    const accounts = emailService.getUserAccounts(req.session.userId);
    return res.render('email-settings', { accounts, error: 'Email, IMAP host, gebruiker en wachtwoord zijn verplicht', saved: false, user: { username: req.session.username } });
  }
  db.prepare(`INSERT INTO email_accounts (user_id, email, name, imap_host, imap_port, imap_secure, imap_user, imap_pass, smtp_host, smtp_port, smtp_secure, smtp_user, smtp_pass)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(
    req.session.userId, email, name || '', imap_host, parseInt(imap_port) || 993, imap_secure === '1' ? 1 : 0,
    imap_user, imap_pass, smtp_host || imap_host, parseInt(smtp_port) || 587, smtp_secure === '1' ? 1 : 0,
    smtp_user || imap_user, smtp_pass || imap_pass
  );
  res.redirect('/email/settings?saved=1');
});

router.post('/settings/:id/delete', (req, res) => {
  const db = getDb();
  db.prepare('DELETE FROM email_accounts WHERE id = ? AND user_id = ?').run(req.params.id, req.session.userId);
  res.redirect('/email/settings');
});

module.exports = router;
