import { Router } from 'express';
import { db } from '../db.js';
import { decrypt } from '../config.js';
import { authRequired } from '../middleware/auth.js';
import { pollUser } from '../services/engine.js';
import { sendMail } from '../services/mail.js';

export const emailsRouter = Router();
emailsRouter.use(authRequired);

// GET /api/emails?status=pending — журнал писем текущего пользователя
emailsRouter.get('/', (req, res) => {
  const status = req.query.status;
  const rows = status
    ? db.prepare('SELECT * FROM emails WHERE user_id = ? AND status = ? ORDER BY received_at DESC, id DESC').all(req.user.id, String(status))
    : db.prepare('SELECT * FROM emails WHERE user_id = ? ORDER BY received_at DESC, id DESC').all(req.user.id);
  res.json({ emails: rows });
});

// POST /api/emails/poll — вручную опросить свою почту прямо сейчас
emailsRouter.post('/poll', async (req, res) => {
  try {
    const result = await pollUser(req.user.id);
    res.json(result);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

function loadOwn(userId, id) {
  return db.prepare('SELECT * FROM emails WHERE id = ? AND user_id = ?').get(Number(id), userId);
}

// PUT /api/emails/:id — отредактировать черновик ответа / получателя
emailsRouter.put('/:id', (req, res) => {
  const email = loadOwn(req.user.id, req.params.id);
  if (!email) return res.status(404).json({ error: 'Письмо не найдено' });
  const draft = req.body?.draft_reply;
  const replyTo = req.body?.reply_to;
  db.prepare('UPDATE emails SET draft_reply = ?, reply_to = ? WHERE id = ?').run(
    draft != null ? String(draft) : email.draft_reply,
    replyTo != null ? String(replyTo) : email.reply_to,
    email.id
  );
  res.json({ ok: true });
});

// POST /api/emails/:id/send — отправить черновик через SMTP
emailsRouter.post('/:id/send', async (req, res) => {
  const email = loadOwn(req.user.id, req.params.id);
  if (!email) return res.status(404).json({ error: 'Письмо не найдено' });
  if (email.status === 'sent') return res.status(400).json({ error: 'Уже отправлено' });
  if (!email.reply_to) return res.status(400).json({ error: 'Не указан адрес получателя' });
  if (!email.draft_reply.trim()) return res.status(400).json({ error: 'Пустой текст ответа' });

  const acc = db.prepare('SELECT * FROM mail_accounts WHERE user_id = ?').get(req.user.id);
  if (!acc || !acc.smtp_host) return res.status(400).json({ error: 'SMTP не настроен' });

  const from = acc.from_email || acc.imap_user || acc.smtp_user;
  const origSubject = email.subject || '';
  const subject = /^re:/i.test(origSubject) ? origSubject : `Re: ${origSubject}`.trim();

  try {
    await sendMail(
      {
        host: acc.smtp_host,
        port: acc.smtp_port,
        secure: !!acc.smtp_secure,
        user: acc.smtp_user,
        pass: decrypt(acc.smtp_pass_enc),
      },
      { from, to: email.reply_to, subject, text: email.draft_reply }
    );
    db.prepare("UPDATE emails SET status = 'sent', error = '', sent_at = datetime('now') WHERE id = ?").run(email.id);
    res.json({ ok: true });
  } catch (err) {
    db.prepare("UPDATE emails SET status = 'error', error = ? WHERE id = ?").run(`SMTP: ${err.message}`, email.id);
    res.status(400).json({ error: `SMTP: ${err.message}` });
  }
});

// POST /api/emails/:id/reject — отклонить (не отправлять)
emailsRouter.post('/:id/reject', (req, res) => {
  const email = loadOwn(req.user.id, req.params.id);
  if (!email) return res.status(404).json({ error: 'Письмо не найдено' });
  db.prepare("UPDATE emails SET status = 'rejected' WHERE id = ?").run(email.id);
  res.json({ ok: true });
});
