const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, fail } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
const path = require('path');

const FREE_PKG = path.join(__dirname, '..', '..', 'dist', 'LiteMall-Free-v1.0.0.tar.gz');
const FULL_PKG = path.join(__dirname, '..', '..', 'dist', 'LiteMall-Full-v1.0.0.tar.gz');

// ===== 下载统计查询（管理员，必须在 :name 路由之前） =====
router.get('/download/stats', authAdmin, (req, res) => {
  const total = get('SELECT COUNT(*) as c FROM download_logs').c;
  const byPkg = all('SELECT pkg_name, COUNT(*) as cnt FROM download_logs GROUP BY pkg_name ORDER BY cnt DESC');
  const today = get("SELECT COUNT(*) as c FROM download_logs WHERE date(created_at)=date('now','localtime')").c;
  const recent = all('SELECT pkg_name, ip, created_at FROM download_logs ORDER BY created_at DESC LIMIT 20');
  return res.json(success({ total, today, byPkg, recent }));
});

// ===== 下载文件（公共API，不需要登录） =====
router.get('/download/:name', (req, res) => {
  const { name } = req.params;
  let filePath;
  if (name === 'lite-free') filePath = FREE_PKG;
  else if (name === 'lite-full') filePath = FULL_PKG;
  else return res.json(fail('下载包不存在'));
  
  const ip = req.ip || req.headers['x-forwarded-for'] || '';
  const ua = (req.headers['user-agent'] || '').slice(0, 200);
  run('INSERT INTO download_logs(pkg_name, ip, user_agent) VALUES(?,?,?)', [name, ip, ua]);
  
  res.download(filePath);
});

module.exports = router;
