import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import Logs from './libs/logs.js';

import userRoutes from './routes/user.js';
import systemRoutes from './routes/system.js';
import psteryRoutes from './routes/pstery.js';
const app = express();

dotenv.config();

// 添加 CORS 支持
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

// 中间件
app.use(express.json({ limit: '10mb' }));
app.use(cookieParser());

app.use((req, res, next) => {
  res.badRequest = (msg) => {
    res.status(400).json({ statusCode: 400, code: -1, message: msg ?? 'Bad Request' });
  }
  res.unauthorized = (msg) => {
    res.status(401).json({ statusCode: 401, code: -1,  message: msg ?? 'Unauthorized' });
  }
  res.notFound = (msg) => {
    res.status(404).json({ statusCode: 404, code: -1,  message: msg ?? 'Not Found' });
  }
  res.serverError = (msg) => {
    res.status(500).json({ statusCode: 500, code: -1,  message: msg ?? 'Internal Server Error' });
  }
  res.sendSuccess = (data, msg) => {
    const response = { statusCode: 200, code: 0,  message: msg ?? 'OK' }
    if (data) {
      response.data = data;
    }
    res.status(200).json(response);
  }
  next();
});

app.use(['/api/user', '/api/auth'], userRoutes);
app.use('/api/system', systemRoutes);
app.use('/api/pstery', psteryRoutes);

// 启动服务
const PORT = process.env.PORT || 9055;
mongoose.connect(process.env.MONGO_URI)
.then(() => {
  Logs.out('MongoDB connected');
  app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
})
.catch(Logs.err);
