'use strict';

/**
 * 赛博游园会 D48 本地 Mock 服务 —— 应用逻辑（可复用，不自动监听端口）。
 *
 * - 内存存储，进程退出后数据重置；
 * - 请求体上限 64KB（65536 字节），超限返回 413；
 * - 拒绝非 JSON 请求体（400）与非法字段（400）；
 * - 仅允许回环地址监听（127.0.0.1 / localhost / ::1）。
 *
 * 本文件导出 createApp()，由 server.js 负责监听，由 test/ 负责集成自检。
 */

const http = require('node:http');

// 请求体大小上限：64KB（65536 字节）
const BODY_LIMIT = 64 * 1024;

// 路径参数 id 只接受纯数字（正整数）
const NON_NEGATIVE_INT = /^\d+$/;

// 初始内存数据（合成练习数据）
const SEED_ITEMS = [{ id: 1, name: '铅笔', quantity: 3 }];

// 仅允许监听回环地址，严禁 0.0.0.0、公网或内网地址
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);

function sendJson(res, statusCode, payload) {
  const body = JSON.stringify(payload, null, 2);
  res.writeHead(statusCode, {
    'Content-Type': 'application/json; charset=utf-8',
    'Content-Length': Buffer.byteLength(body)
  });
  res.end(body);
}

function sendError(res, statusCode, message, errors = []) {
  sendJson(res, statusCode, { code: statusCode, message, errors });
}

/**
 * 校验创建条目请求体。
 * 规则：
 *  - 顶层必须是 JSON 对象（数组、null、原始类型均拒绝）；
 *  - name：必填，非空字符串（去除首尾空白后仍非空）；
 *  - quantity：必填，正整数（≥1 的整数）；
 *  - 仅允许 name、quantity 两个字段，出现额外字段即 400。
 * 返回 { ok, message, errors, value? }
 */
function validatePayload(body) {
  if (body === null || typeof body !== 'object' || Array.isArray(body)) {
    return {
      ok: false,
      message: '请求体必须是 JSON 对象',
      errors: ['请求体必须是 JSON 对象，不能是数组或其他类型']
    };
  }

  const errors = [];
  const allowed = new Set(['name', 'quantity']);

  for (const key of Object.keys(body)) {
    if (!allowed.has(key)) {
      errors.push(`不允许的字段「${key}」（仅允许 name、quantity）`);
    }
  }

  if (!Object.prototype.hasOwnProperty.call(body, 'name')) {
    errors.push('缺少必填字段「name」');
  } else if (typeof body.name !== 'string' || body.name.trim() === '') {
    errors.push('字段「name」必须是非空字符串');
  }

  if (!Object.prototype.hasOwnProperty.call(body, 'quantity')) {
    errors.push('缺少必填字段「quantity」');
  } else if (
    typeof body.quantity !== 'number' ||
    !Number.isInteger(body.quantity) ||
    body.quantity < 1
  ) {
    errors.push('字段「quantity」必须是正整数（≥1 的整数）');
  }

  if (errors.length > 0) {
    return { ok: false, message: '请求体校验失败', errors };
  }
  return {
    ok: true,
    message: '',
    errors: [],
    value: { name: body.name.trim(), quantity: body.quantity }
  };
}

/**
 * 读取并解析请求体。返回 Promise：
 *  - { handled: true }：已自行响应（415 / 413 / 400 空体 / 400 非 JSON / 400 读取错误）；
 *  - { handled: false, body }：解析成功，body 交给调用方校验。
 */
function readRequestBody(req, res) {
  return new Promise((resolve) => {
    const resolveHandled = () => resolve({ handled: true });
    const resolveBody = (body) => resolve({ handled: false, body });

    const contentType = (req.headers['content-type'] || '').toLowerCase();
    if (contentType && !contentType.includes('application/json')) {
      sendError(res, 415, 'Content-Type 必须是 application/json');
      return resolveHandled();
    }

    let chunks = [];
    let received = 0;
    let handled = false;

    req.on('data', (chunk) => {
      if (handled) return;
      received += chunk.length;
      if (received > BODY_LIMIT) {
        handled = true;
        chunks = [];
        sendError(res, 413, `请求体超过 ${BODY_LIMIT} 字节（64KB）上限`);
        resolveHandled();
        return;
      }
      chunks.push(chunk);
    });

    req.on('end', () => {
      if (handled) return;
      handled = true;
      const raw = Buffer.concat(chunks).toString('utf8');
      if (raw.trim() === '') {
        sendError(res, 400, '请求体不能为空，请提供 JSON 对象');
        return resolveHandled();
      }
      let body;
      try {
        body = JSON.parse(raw);
      } catch (_err) {
        sendError(res, 400, '请求体不是合法的 JSON');
        return resolveHandled();
      }
      resolveBody(body);
    });

    req.on('error', () => {
      if (handled) return;
      handled = true;
      if (!res.headersSent) {
        sendError(res, 400, '读取请求体时发生错误');
      }
      resolveHandled();
    });
  });
}

/**
 * 工厂函数：返回一个未启动的 http.Server，状态隔离，便于测试。
 */
function createApp() {
  let items = SEED_ITEMS.map((it) => ({ ...it }));
  let nextId = 2;

  async function handleCreate(req, res) {
    const { handled, body } = await readRequestBody(req, res);
    if (handled) return;

    const result = validatePayload(body);
    if (!result.ok) {
      return sendError(res, 400, result.message, result.errors);
    }
    const item = { id: nextId++, name: result.value.name, quantity: result.value.quantity };
    items.push(item);
    return sendJson(res, 201, item);
  }

  const server = http.createServer((req, res) => {
    // CORS：允许离线打开的本地 HTML（file:// 等来源）通过 fetch 跨域调用。
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.setHeader('Access-Control-Max-Age', '86400');

    if (req.method === 'OPTIONS') {
      res.writeHead(204);
      return res.end();
    }

    let url;
    try {
      url = new URL(req.url, 'http://127.0.0.1');
    } catch (_err) {
      return sendError(res, 400, '请求 URL 无法解析');
    }
    const path = url.pathname;
    const method = req.method;

    // 根路径：服务自述，便于浏览器直接查看
    if (method === 'GET' && path === '/') {
      return sendJson(res, 200, {
        service: '赛博游园会 D48 本地 Mock 服务',
        version: '1.0.0',
        endpoints: [
          'GET /items —— 获取条目列表',
          'GET /items/{id} —— 获取单个条目（不存在返回 404）',
          'POST /items —— 创建条目（非法返回 400）'
        ],
        note: '合成练习数据，内存存储，服务重启后数据重置'
      });
    }

    if (path === '/items') {
      if (method === 'GET') return sendJson(res, 200, items);
      if (method === 'POST') return handleCreate(req, res);
      return sendError(res, 405, `不支持的请求方法：${method} ${path}`);
    }

    const match = path.match(/^\/items\/([^/]+)$/);
    if (match) {
      if (method !== 'GET') {
        return sendError(res, 405, `不支持的请求方法：${method} ${path}`);
      }
      const rawId = match[1];
      if (!NON_NEGATIVE_INT.test(rawId)) {
        return sendError(res, 400, `路径参数 id 必须是正整数，收到「${rawId}」`);
      }
      const id = Number(rawId);
      const item = items.find((it) => it.id === id);
      if (!item) {
        return sendError(res, 404, `未找到 id 为 ${id} 的条目`);
      }
      return sendJson(res, 200, item);
    }

    return sendError(res, 404, `未找到资源：${method} ${path}`);
  });

  return server;
}

module.exports = { createApp, BODY_LIMIT, validatePayload, LOOPBACK_HOSTS };