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

import controlRoutes from './routes/control.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/control', controlRoutes);

// 启动服务
const PORT = 9056;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
