(function () {
  const EVENT_FILENAME = "./event.json";

  function initRequest() {
    if (!fs.existsSync(EVENT_FILENAME)) {
      console.error("Event payload file does not exist:", EVENT_FILENAME);
      return;
    }

    const raw = fs.readFileSync(EVENT_FILENAME, "utf-8");

    try {
      return JSON.parse(raw);
    } catch (error) {
      console.error("Error parsing event payload:", error);
    }
  }

  function initResponse() {
    return {
      statusCode: 200,
      headers: {},
      body: null,
      setStatus(code) {
        if (Number.isFinite(code)) {
          this.statusCode = Math.trunc(code);
        }
        return this;
      },
      setHeader(name, value) {
        if (typeof name === "string") {
          this.headers[name] = value;
        }
        return this;
      },
      setHeaders(map) {
        if (isPlainObject(map)) {
          for (const key in map) {
            if (Object.prototype.hasOwnProperty.call(map, key)) {
              this.headers[key] = map[key];
            }
          }
        }
        return this;
      },
      removeHeader(name) {
        if (typeof name === "string") {
          delete this.headers[name];
        }
        return this;
      },
      reset() {
        this.statusCode = 200;
        this.headers = {};
        this.body = null;
        return this;
      },
      send(payload) {
        this.body = payload;
        return this;
      },
      json(payload) {
        try {
          this.body = JSON.stringify(payload);
        } catch (_error) {
          this.body = null;
        }
        if (!("content-type" in this.headers)) {
          this.headers["content-type"] = "application/json";
        }
        return this;
      },
    };
  }

  globalThis.req = initRequest();
  globalThis.res = initResponse();
})();
