import { Router } from 'express';
import { db } from '../db.js';
import { authRequired } from '../middleware/auth.js';
import { generateReply } from '../services/claude.js';

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

// POST /api/generate  { from, subject, body } — сгенерировать черновик ответа
// от лица текущего пользователя (берём его профиль).
generateRouter.post('/', async (req, res) => {
  const incoming = {
    from: String(req.body?.from || ''),
    subject: String(req.body?.subject || ''),
    body: String(req.body?.body || ''),
  };
  if (!incoming.body.trim()) {
    return res.status(400).json({ error: 'Укажите текст входящего письма' });
  }

  const profile = db.prepare(
    'SELECT full_name, company, position, signature FROM profiles WHERE user_id = ?'
  ).get(req.user.id) || { full_name: '', company: '', position: '', signature: '' };

  try {
    const draft = await generateReply({ incoming, profile });
    res.json({ draft });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});
