// Scratch driver for pingdotgg/t3code#26534: posts guest messages through the server's real
// readSubmission as multipart FormData (what GuestComposer sends) and as JSON, and prints the result.
// Copy to apps/server/src/guest/ and run: OUT=<file> vp test run src/guest/repro-guest-multipart.test.ts
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/http";
import * as fs from "node:fs";
import { readSubmission } from "./http.ts";

const run = (text: string, multipart: boolean) =>
  Effect.gen(function* () {
    let init: RequestInit;
    if (multipart) {
      const form = new FormData();
      form.append("shareId", "share-1");
      form.append("text", text);
      init = { method: "POST", body: form };
    } else {
      init = {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ shareId: "share-1", text }),
      };
    }
    const request = HttpServerRequest.fromWeb(
      new Request("http://localhost/api/guest/messages?share=share-1", init),
    );
    const s = yield* readSubmission.pipe(
      Effect.provideService(HttpServerRequest.HttpServerRequest, request),
    );
    if (s === null) return "REJECTED (route answers 400 \"The request was not valid.\")";
    const t = s.fields.text;
    return `accepted, stored length ${t.length}, CRLF ${(t.match(/\r\n/g) ?? []).length}, equals typed text: ${t === text}`;
  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));

it.effect("guest multipart transcript", () =>
  Effect.gen(function* () {
    const variants: Array<[string, string]> = [
      ["reporter: 3999 chars, 1999 line breaks", "a\n".repeat(2000).slice(0, 3999)],
      ["4000-char paste of 80-char paragraphs (49 line breaks)", ("x".repeat(79) + "\n").repeat(50).slice(0, 3999) + "!"],
      ["short 3-paragraph message (2 line breaks)", "Hi,\nplease check the build.\nThanks"],
      ["4000 chars, single line", "z".repeat(4000)],
      ["4001 chars, single line (really too long)", "z".repeat(4001)],
      ["2001 chars + 2000 line breaks = 4001 chars typed (really too long)", "a\n".repeat(2000) + "a"],
    ];
    const out: string[] = [];
    for (const [label, text] of variants) {
      out.push(`${label} [typed length ${text.length}]`);
      out.push(`  multipart: ${yield* run(text, true)}`);
      out.push(`  json:      ${yield* run(text, false)}`);
    }
    fs.writeFileSync(process.env.OUT ?? "/dev/stdout", out.join("\n") + "\n");
  }),
);
