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

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

function mapSignal(row) {
  return {
    id: row.id,
    pair: row.pair,
    pairName: row.pair_name,
    type: row.type,
    status: row.status,
    result: row.result,
    sentAt: row.sent_at,
    closedAt: row.closed_at,
    lastUpdateAt: row.last_update_at,
  };
}

router.get('/active', (req, res) => {
  const rows = db.prepare(`
    SELECT * FROM signals WHERE status = 'active' ORDER BY sent_at DESC
  `).all();
  res.json({ signals: rows.map(mapSignal), count: rows.length });
});

router.get('/recently-closed', (req, res) => {
  const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
  const rows = db.prepare(`
    SELECT * FROM signals
    WHERE status = 'closed' AND closed_at >= ?
    ORDER BY closed_at DESC
  `).all(since);
  res.json({ signals: rows.map(mapSignal), count: rows.length });
});

router.get('/archive', (req, res) => {
  const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
  const page = Math.max(1, parseInt(req.query.page) || 1);
  const limit = Math.min(50, parseInt(req.query.limit) || 20);
  const offset = (page - 1) * limit;

  const total = db.prepare(`
    SELECT COUNT(*) as c FROM signals WHERE status = 'closed' AND closed_at < ?
  `).get(since).c;

  const rows = db.prepare(`
    SELECT * FROM signals WHERE status = 'closed' AND closed_at < ?
    ORDER BY closed_at DESC LIMIT ? OFFSET ?
  `).all(since, limit, offset);

  res.json({ signals: rows.map(mapSignal), page, totalPages: Math.ceil(total / limit), total });
});

router.get('/summary/counts', (req, res) => {
  const active = db.prepare(`SELECT COUNT(*) as c FROM signals WHERE status = 'active'`).get().c;
  const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
  const recentlyClosed = db.prepare(`
    SELECT COUNT(*) as c FROM signals WHERE status = 'closed' AND closed_at >= ?
  `).get(since).c;
  const lastUpdate = db.prepare(`
    SELECT MAX(last_update_at) as t FROM signals
  `).get().t;

  res.json({ active, recentlyClosed, lastUpdate });
});

router.get('/history', (req, res) => {
  const period = req.query.period || 'all';
  const result = req.query.result;
  const search = req.query.search?.trim();
  const page = Math.max(1, parseInt(req.query.page) || 1);
  const limit = Math.min(50, parseInt(req.query.limit) || 15);
  const offset = (page - 1) * limit;

  let sql = `SELECT * FROM signals WHERE status = 'closed'`;
  const params = [];

  const since = buildStatsWhere(period === 'today' ? 'today' : period === 'week' ? 'week' : period === 'month' ? 'month' : null);
  if (since) {
    sql += ` AND closed_at >= ?`;
    params.push(since.toISOString());
  }
  if (result === 'profit' || result === 'loss') {
    sql += ` AND result = ?`;
    params.push(result);
  }
  if (search) {
    sql += ` AND (pair LIKE ? OR pair_name LIKE ?)`;
    params.push(`%${search}%`, `%${search}%`);
  }

  const countSql = sql.replace('SELECT *', 'SELECT COUNT(*) as c');
  const total = db.prepare(countSql).get(...params).c;

  sql += ` ORDER BY closed_at DESC LIMIT ? OFFSET ?`;
  const rows = db.prepare(sql).all(...params, limit, offset);

  res.json({ signals: rows.map(mapSignal), page, totalPages: Math.ceil(total / limit), total });
});

router.get('/:id', (req, res) => {
  const row = db.prepare('SELECT * FROM signals WHERE id = ?').get(req.params.id);
  if (!row) return res.status(404).json({ error: 'سیگنال یافت نشد' });
  res.json(mapSignal(row));
});

export default router;
