import { Router } from 'express';
import { db, getSetting } from '../db.js';
import { authRequired } from '../middleware/auth.js';

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

// Счётчики писем по статусам для набора строк.
function countByStatus(rows) {
  const out = { pending: 0, sent: 0, rejected: 0, error: 0, total: 0 };
  for (const r of rows) {
    out[r.status] = r.c;
    out.total += r.c;
  }
  return out;
}

// GET /api/stats — сводка под роль текущего пользователя.
statsRouter.get('/', (req, res) => {
  // Личные счётчики писем
  const mineRows = db.prepare(
    'SELECT status, COUNT(*) AS c FROM emails WHERE user_id = ? GROUP BY status'
  ).all(req.user.id);

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

  const payload = {
    mine: countByStatus(mineRows),
    account: {
      imap_configured: !!acc.imap_host && !!acc.imap_user,
      smtp_configured: !!acc.smtp_host && !!acc.smtp_user,
      autoreply_enabled: !!acc.poll_enabled,
      profile_complete: !!profile.full_name,
    },
    poll_interval: Number(getSetting('poll_interval_seconds')) || 60,
  };

  // Глобальные счётчики — только для админа
  if (req.user.role === 'admin') {
    const globalRows = db.prepare('SELECT status, COUNT(*) AS c FROM emails GROUP BY status').all();
    payload.global = {
      users: db.prepare('SELECT COUNT(*) AS c FROM users').get().c,
      training_files: db.prepare('SELECT COUNT(*) AS c FROM training_files').get().c,
      api_key_set: !!getSetting('anthropic_api_key'),
      model: getSetting('claude_model') || 'claude-opus-4-8',
      autoreply_users: db.prepare('SELECT COUNT(*) AS c FROM mail_accounts WHERE poll_enabled = 1').get().c,
      emails: countByStatus(globalRows),
    };
  }

  res.json({ stats: payload });
});
