/**
 * aff-monitor — 主入口
 * 前台公开 + 后台登录管理
 */
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3900;

// ── 中间件 ──
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// Session
app.use(session({
  secret: process.env.SESSION_SECRET || 'vps-monitor-default-secret',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 7 * 24 * 60 * 60 * 1000, // 7 天
    httpOnly: true,
  },
}));

// 把登录状态传给所有模板
app.use((req, res, next) => {
  res.locals.isAdmin = !!req.session.isAdmin;
  next();
});

// ── 认证中间件 ──
function requireAdmin(req, res, next) {
  if (req.session.isAdmin) return next();
  res.redirect('/admin/login');
}

// ── 前台公开路由（无需登录） ──
app.use('/', require('./routes/public'));

// ── 登录/登出路由 ──
app.use('/admin', require('./routes/auth'));

// ── 后台管理路由（需要登录） ──
app.use('/admin', requireAdmin, require('./routes/admin'));
app.use('/admin/merchants', requireAdmin, require('./routes/merchants'));
app.use('/admin/products', requireAdmin, require('./routes/products'));
app.use('/admin/channels', requireAdmin, require('./routes/channels'));
app.use('/admin/aff-links', requireAdmin, require('./routes/affLinks'));
app.use('/admin/tasks', requireAdmin, require('./routes/tasks'));
app.use('/admin/settings', requireAdmin, require('./routes/settings'));

// ── 启动 ──
app.listen(PORT, () => {
  console.log(`🚀 vps补货监控 运行中: http://localhost:${PORT}`);

  // 自动启动调度器（如果配置了 SCHEDULER_ENABLED=true）
  if (process.env.SCHEDULER_ENABLED === 'true') {
    const scheduler = require('./utils/scheduler');
    scheduler.start();
  }
});
