const http = require('http');
const url = require('url');
const mockConfig = require('./mock/mockData.js');

const PORT = 3001;
const BASE_PATH = '/mock-api';

function getMockData(requestUrl, method) {
  const mockDataList = mockConfig.getMockDataList();
  for (const key in mockDataList) {
    const item = mockDataList[key];
    if (item.url === requestUrl && item.method.toLowerCase() === method.toLowerCase()) {
      return item;
    }
  }
  return null;
}

function sendJson(res, statusCode, data) {
  res.writeHead(statusCode, {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization, belongSystemId, belongSystemName'
  });
  res.end(JSON.stringify(data));
}

const server = http.createServer((req, res) => {
  if (req.method === 'OPTIONS') {
    sendJson(res, 204, null);
    return;
  }

  const parsedUrl = url.parse(req.url, true);
  const pathname = parsedUrl.pathname;
  const method = req.method;

  if (!pathname.startsWith(BASE_PATH)) {
    sendJson(res, 404, { code: 404, msg: 'Not Found', data: null });
    return;
  }

  const apiPath = pathname.replace(BASE_PATH, '');

  console.log(`[Mock Server] 收到请求: ${method} ${apiPath}`);
  if (Object.keys(parsedUrl.query).length > 0) {
    console.log(`[Mock Server] Query参数:`, parsedUrl.query);
  }

  const mockData = getMockData(apiPath, method);
  if (mockData) {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      if (body) {
        try {
          console.log(`[Mock Server] Body参数:`, JSON.parse(body));
        } catch (e) {
          console.log(`[Mock Server] Body参数:`, body);
        }
      }

      setTimeout(() => {
        sendJson(res, 200, mockData.response);
        console.log(`[Mock Server] 返回Mock数据\n`);
      }, mockData.delay || 300);
    });
  } else {
    console.log(`[Mock Server] 未找到Mock配置: ${method} ${apiPath}\n`);
    sendJson(res, 404, { code: 404, msg: 'Mock接口不存在', data: null });
  }
});

server.listen(PORT, () => {
  console.log('==========================================');
  console.log('🟢 Mock服务器已启动');
  console.log(`📡 监听地址: http://localhost:${PORT}`);
  console.log(`🔗 接口前缀: ${BASE_PATH}`);
  console.log('==========================================');

  const mockList = mockConfig.getMockDataList();
  console.log('\n已注册的Mock接口:');
  Object.keys(mockList).forEach(key => {
    const item = mockList[key];
    console.log(`  ${item.method.toUpperCase().padEnd(6)} ${item.url}`);
  });
  console.log('==========================================\n');
});
