import { Router } from 'express';
import { db } from '../db.js';
import { authMiddleware } from '../middleware/auth.js';
import { buildStatsWhere, computeSignalStats } from '../utils/stats.js';

const router = Router();
router.use(authMiddleware);

const PERSIAN_MONTHS = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'];
const WEEK_DAYS = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه'];

function getClosedSignals(since = null) {
  let sql = `SELECT * FROM signals WHERE status = 'closed'`;
  const params = [];
  if (since) {
    sql += ` AND closed_at >= ?`;
    params.push(since.toISOString());
  }
  return db.prepare(sql).all(...params);
}

router.get('/stats', (req, res) => {
  const period = req.query.period || 'all';
  const since = buildStatsWhere(period === 'today' ? 'today' : period === '7days' ? '7days' : period === '30days' ? '30days' : null);
  const rows = getClosedSignals(since);
  const stats = computeSignalStats(rows);

  const todaySince = buildStatsWhere('today');
  const weekSince = buildStatsWhere('week');
  const todayStats = computeSignalStats(getClosedSignals(todaySince));
  const weekStats = computeSignalStats(getClosedSignals(weekSince));

  res.json({
    ...stats,
    today: todayStats,
    week: weekStats,
  });
});

router.get('/chart/monthly', (req, res) => {
  const rows = db.prepare(`
    SELECT strftime('%Y-%m', closed_at) as month, result
    FROM signals WHERE status = 'closed' AND closed_at IS NOT NULL
  `).all();

  const byMonth = {};
  for (const r of rows) {
    if (!r.month) continue;
    if (!byMonth[r.month]) byMonth[r.month] = { profit: 0, loss: 0 };
    if (r.result === 'profit') byMonth[r.month].profit++;
    else if (r.result === 'loss') byMonth[r.month].loss++;
  }

  const sorted = Object.keys(byMonth).sort().slice(-6);
  const data = sorted.map((m, i) => {
    const { profit, loss } = byMonth[m];
    const total = profit + loss;
    const rate = total > 0 ? Math.round((profit / total) * 10000) / 100 : 0;
    const [, monthNum] = m.split('-');
    const label = PERSIAN_MONTHS[parseInt(monthNum, 10) - 1] || m;
    return { month: m, label, successRate: rate, profit, loss };
  });

  res.json({ data });
});

router.get('/chart/distribution', (req, res) => {
  const period = req.query.period || 'all';
  const since = buildStatsWhere(period === 'today' ? 'today' : period === '7days' ? '7days' : period === '30days' ? '30days' : null);
  const rows = getClosedSignals(since);
  const stats = computeSignalStats(rows);
  res.json({
    profit: stats.profit,
    loss: stats.loss,
    profitPercent: stats.total > 0 ? stats.successRate : 0,
    lossPercent: stats.total > 0 ? Math.round((stats.loss / stats.total) * 10000) / 100 : 0,
  });
});

router.get('/chart/weekdays', (req, res) => {
  const rows = db.prepare(`
    SELECT closed_at, result FROM signals WHERE status = 'closed' AND closed_at IS NOT NULL
  `).all();

  const days = Array(7).fill(null).map(() => ({ profit: 0, loss: 0 }));
  for (const r of rows) {
    const d = new Date(r.closed_at);
    const dow = (d.getDay() + 1) % 7;
    if (r.result === 'profit') days[dow].profit++;
    else if (r.result === 'loss') days[dow].loss++;
  }

  const data = days.map((d, i) => {
    const total = d.profit + d.loss;
    return {
      day: WEEK_DAYS[i],
      successRate: total > 0 ? Math.round((d.profit / total) * 10000) / 100 : 0,
      profit: d.profit,
      loss: d.loss,
    };
  });

  res.json({ data });
});

router.get('/overview', (req, res) => {
  const user = db.prepare('SELECT full_name, subscription_expires_at, plan_months FROM users WHERE id = ?').get(req.user.id);
  const allClosed = getClosedSignals();
  const stats = computeSignalStats(allClosed);
  const todayStats = computeSignalStats(getClosedSignals(buildStatsWhere('today')));
  const weekStats = computeSignalStats(getClosedSignals(buildStatsWhere('week')));
  const summary = db.prepare(`
    SELECT MAX(last_update_at) as lastUpdate FROM signals
  `).get();

  res.json({
    user: {
      fullName: user?.full_name,
      subscriptionExpiresAt: user?.subscription_expires_at,
      planMonths: user?.plan_months,
      isPremium: (user?.plan_months || 0) >= 6,
    },
    stats: { ...stats, today: todayStats, week: weekStats },
    lastUpdate: summary?.lastUpdate,
  });
});

export default router;
