import 'dotenv/config';

import express from 'express';

import Logs from "./libs/logs.js";
import requireInternalToken from './middleware/requireInternalToken.js';
import requirePinnacleProxyAuth from './middleware/requirePinnacleProxyAuth.js';
import pinnacleProxyRoutes from './routes/pinnacleProxy.js';
import tradingRoutes from './routes/trading.js';

import { startSyncMarketsData } from "./libs/syncData.js";

const app = express();

app.use((req, res, next) => {
  const origin = req.headers.origin;
  res.header('Access-Control-Allow-Origin', origin || '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Internal-Token, X-Api-User, X-Api-Timestamp, X-Api-Nonce, X-Api-Signature');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Vary', 'Origin');

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

app.use(express.json({ limit: '10mb' }));

app.use((req, res, next) => {
  res.badRequest = (data, msg) => {
    if (!msg && typeof data === 'string') {
      msg = data;
      data = undefined;
    }
    return res.status(400).json({ statusCode: 400, code: -1, message: msg ?? 'Bad Request', data });
  }
  res.serverError = (data, msg) => {
    if (!msg && typeof data === 'string') {
      msg = data;
      data = undefined;
    }
    return res.status(500).json({ statusCode: 500, code: -1, message: msg ?? 'Internal Server Error', data });
  }
  res.unauthorized = (data, msg) => {
    if (!msg && typeof data === 'string') {
      msg = data;
      data = undefined;
    }
    return res.status(401).json({ statusCode: 401, code: -1, message: msg ?? 'Unauthorized', data });
  }
  res.sendSuccess = (data, msg) => {
    const response = { statusCode: 200, code: 0, message: msg ?? 'OK' }
    if (data !== undefined) {
      response.data = data;
    }
    return res.status(200).json(response);
  }
  res.sendError = (err) => {
    if (err.cause === 400 || err.status === 400) {
      return res.badRequest(err.data, err.message);
    }
    return res.serverError(err.data, err.message);
  }
  next();
});

app.get('/health', (req, res) => {
  res.sendSuccess({ service: 'polymarket', status: 'ok' });
});

app.use('/api/pinnacle', requirePinnacleProxyAuth, pinnacleProxyRoutes);
app.use('/api/trading', requireInternalToken, tradingRoutes);

// 启动服务
const PORT = process.env.PORT || 9057;
app.listen(PORT, () => Logs.out(`Pinnacle service running on port ${PORT}`));

startSyncMarketsData();
