import { Router } from 'express';
import { db } from '../db.js';
import { encrypt, decrypt } from '../config.js';
import { authRequired } from '../middleware/auth.js';
import { testImap, testSmtp } from '../services/mail.js';

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

function loadAccount(userId) {
  return db.prepare('SELECT * FROM mail_accounts WHERE user_id = ?').get(userId);
}

// Приводим настройки к виду для подключения, подставляя сохранённый пароль,
// если в запросе пароль пустой (значит пользователь его не менял).
function resolveImap(userId, body) {
  const saved = loadAccount(userId);
  const pass = body.imap_pass ? body.imap_pass : (saved ? decrypt(saved.imap_pass_enc) : '');
  return {
    host: body.imap_host ?? saved?.imap_host ?? '',
    port: body.imap_port ?? saved?.imap_port ?? 993,
    secure: body.imap_secure ?? (saved ? !!saved.imap_secure : true),
    user: body.imap_user ?? saved?.imap_user ?? '',
    pass,
  };
}

function resolveSmtp(userId, body) {
  const saved = loadAccount(userId);
  const pass = body.smtp_pass ? body.smtp_pass : (saved ? decrypt(saved.smtp_pass_enc) : '');
  return {
    host: body.smtp_host ?? saved?.smtp_host ?? '',
    port: body.smtp_port ?? saved?.smtp_port ?? 465,
    secure: body.smtp_secure ?? (saved ? !!saved.smtp_secure : true),
    user: body.smtp_user ?? saved?.smtp_user ?? '',
    pass,
  };
}

// GET /api/mail — настройки почты (БЕЗ паролей, только флаги «пароль задан»)
mailRouter.get('/', (req, res) => {
  const a = loadAccount(req.user.id) || {};
  res.json({
    mail: {
      imap_host: a.imap_host || '',
      imap_port: a.imap_port || 993,
      imap_secure: a.imap_secure == null ? true : !!a.imap_secure,
      imap_user: a.imap_user || '',
      imap_pass_set: !!a.imap_pass_enc,
      smtp_host: a.smtp_host || '',
      smtp_port: a.smtp_port || 465,
      smtp_secure: a.smtp_secure == null ? true : !!a.smtp_secure,
      smtp_user: a.smtp_user || '',
      smtp_pass_set: !!a.smtp_pass_enc,
      from_email: a.from_email || '',
      poll_enabled: a.poll_enabled == null ? false : !!a.poll_enabled,
    },
  });
});

// PUT /api/mail — сохранить настройки. Пустой пароль => не менять существующий.
mailRouter.put('/', (req, res) => {
  const b = req.body || {};
  const saved = loadAccount(req.user.id);

  const imap_pass_enc = b.imap_pass
    ? encrypt(b.imap_pass)
    : (saved ? saved.imap_pass_enc : '');
  const smtp_pass_enc = b.smtp_pass
    ? encrypt(b.smtp_pass)
    : (saved ? saved.smtp_pass_enc : '');

  db.prepare(`
    INSERT INTO mail_accounts (
      user_id, imap_host, imap_port, imap_secure, imap_user, imap_pass_enc,
      smtp_host, smtp_port, smtp_secure, smtp_user, smtp_pass_enc,
      from_email, poll_enabled
    ) VALUES (
      @user_id, @imap_host, @imap_port, @imap_secure, @imap_user, @imap_pass_enc,
      @smtp_host, @smtp_port, @smtp_secure, @smtp_user, @smtp_pass_enc,
      @from_email, @poll_enabled
    )
    ON CONFLICT(user_id) DO UPDATE SET
      imap_host = excluded.imap_host, imap_port = excluded.imap_port,
      imap_secure = excluded.imap_secure, imap_user = excluded.imap_user,
      imap_pass_enc = excluded.imap_pass_enc,
      smtp_host = excluded.smtp_host, smtp_port = excluded.smtp_port,
      smtp_secure = excluded.smtp_secure, smtp_user = excluded.smtp_user,
      smtp_pass_enc = excluded.smtp_pass_enc,
      from_email = excluded.from_email, poll_enabled = excluded.poll_enabled
  `).run({
    user_id: req.user.id,
    imap_host: String(b.imap_host || ''),
    imap_port: Number(b.imap_port) || 993,
    imap_secure: b.imap_secure ? 1 : 0,
    imap_user: String(b.imap_user || ''),
    imap_pass_enc,
    smtp_host: String(b.smtp_host || ''),
    smtp_port: Number(b.smtp_port) || 465,
    smtp_secure: b.smtp_secure ? 1 : 0,
    smtp_user: String(b.smtp_user || ''),
    smtp_pass_enc,
    from_email: String(b.from_email || ''),
    poll_enabled: b.poll_enabled ? 1 : 0,
  });

  res.json({ ok: true });
});

// POST /api/mail/test-imap — проверить IMAP (использует переданные или сохранённые данные)
mailRouter.post('/test-imap', async (req, res) => {
  try {
    const result = await testImap(resolveImap(req.user.id, req.body || {}));
    res.json({ ok: true, message: `Подключение успешно. Писем в INBOX: ${result.total}` });
  } catch (err) {
    res.status(400).json({ ok: false, error: err.message });
  }
});

// POST /api/mail/test-smtp — проверить SMTP
mailRouter.post('/test-smtp', async (req, res) => {
  try {
    await testSmtp(resolveSmtp(req.user.id, req.body || {}));
    res.json({ ok: true, message: 'Подключение успешно. SMTP готов к отправке.' });
  } catch (err) {
    res.status(400).json({ ok: false, error: err.message });
  }
});
