import { db } from '../db.js';
import { decrypt } from '../config.js';
import { processInbox } from './imap.js';
import { isApplicationEmail, processApplication } from './applicationForm.js';
import { generateReply } from './claude.js';

// Опрос почты одного пользователя: читаем непрочитанные → создаём черновики.
// Ничего не отправляем (режим ручного одобрения).
export async function pollUser(userId) {
  const acc = db.prepare('SELECT * FROM mail_accounts WHERE user_id = ?').get(userId);
  if (!acc || !acc.imap_host || !acc.imap_user) {
    return { polled: false, reason: 'IMAP не настроен' };
  }
  const profile = db.prepare(
    'SELECT full_name, company, position, signature FROM profiles WHERE user_id = ?'
  ).get(userId) || { full_name: '', company: '', position: '', signature: '' };

  const account = {
    host: acc.imap_host,
    port: acc.imap_port,
    secure: !!acc.imap_secure,
    user: acc.imap_user,
    pass: decrypt(acc.imap_pass_enc),
  };

  let created = 0;
  const insert = db.prepare(`
    INSERT OR IGNORE INTO emails
      (user_id, message_id, from_addr, from_name, subject, body, draft_reply, reply_to, kind, status, error)
    VALUES (@user_id, @message_id, @from_addr, @from_name, @subject, @body, @draft_reply, @reply_to, @kind, @status, @error)
  `);

  await processInbox(account, async (email) => {
    // уже обрабатывали это письмо?
    const exists = db.prepare('SELECT id FROM emails WHERE user_id = ? AND message_id = ?')
      .get(userId, email.messageId);
    if (exists) return true; // помечаем \Seen и идём дальше

    const isApp = isApplicationEmail(email.from);
    const kind = isApp ? 'application' : 'normal';
    let draft = '';
    let replyTo = email.from;
    let status = 'pending';
    let error = '';

    try {
      if (isApp) {
        const r = processApplication({ body: email.text, subject: email.subject });
        draft = r.body;
        replyTo = r.to || '';
        if (!r.ok) {
          status = 'error';
          error = r.warnings.join('; ');
        }
      } else {
        draft = await generateReply({
          incoming: { from: email.from, subject: email.subject, body: email.text },
          profile,
        });
      }
    } catch (e) {
      status = 'error';
      error = e.message;
    }

    insert.run({
      user_id: userId,
      message_id: email.messageId,
      from_addr: email.from,
      from_name: email.fromName,
      subject: email.subject,
      body: email.text,
      draft_reply: draft,
      reply_to: replyTo,
      kind,
      status,
      error,
    });
    created++;
    return true;
  });

  return { polled: true, created };
}

// Опрос всех пользователей с включённым автоответчиком и настроенным IMAP.
export async function pollAllUsers() {
  const users = db.prepare(`
    SELECT u.id FROM users u
    JOIN mail_accounts m ON m.user_id = u.id
    WHERE m.poll_enabled = 1 AND m.imap_host <> '' AND m.imap_user <> ''
  `).all();

  for (const u of users) {
    try {
      const r = await pollUser(u.id);
      if (r.created) console.log(`[engine] user ${u.id}: создано черновиков ${r.created}`);
    } catch (e) {
      console.error(`[engine] ошибка опроса user ${u.id}:`, e.message);
    }
  }
}
