const express = require('express');
const cors = require('cors');
const path = require('path');

// 初始化数据库
require('./db/init');

const authRoutes = require('./routes/auth');
const ticketRoutes = require('./routes/tickets');
const lotteryRoutes = require('./routes/lottery');
const ocrRoutes = require('./routes/ocr');

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

// 中间件
app.use(cors());
app.use(express.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API 路由
app.use('/api/auth', authRoutes);
app.use('/api/tickets', ticketRoutes);
app.use('/api/lottery', lotteryRoutes);
app.use('/api/ocr', ocrRoutes);

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', time: new Date().toISOString() });
});

// 静态文件服务 - 前端构建产物
const clientDist = path.join(__dirname, '../client/dist');
app.use(express.static(clientDist));

// SPA 路由 - 所有非 API 请求返回 index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(clientDist, 'index.html'));
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`服务器运行在 http://0.0.0.0:${PORT}`);
});
