// MailCraft quickstart in TypeScript: fetch only, no packages (Node 22.6+).
//
// Creates an inbox, emails you from it, waits for your reply on the event feed,
// reads the thread and answers. It sends real mail.
//
//   export MAILCRAFT_API_KEY=mc_live_...
//   export MY_EMAIL=you@example.com
//   node --experimental-strip-types quickstart.mts

const API = "https://api.mailcraft.ntconnect.com";
const KEY = process.env.MAILCRAFT_API_KEY ?? "";

async function call(method: string, path: string, body?: unknown, idempotent = false): Promise<any> {
  const headers: Record<string, string> = { Authorization: `Bearer ${KEY}` };
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (idempotent) headers["Idempotency-Key"] = crypto.randomUUID();
  const res = await fetch(API + path, {
    method,
    headers,
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`${res.status} ${json.title}: ${json.detail ?? ""}`);
  return json;
}

// 2. Create an inbox.
const box = await call("POST", "/v0/inboxes", { displayName: "Quickstart" });
console.log("inbox:", box.address);

// Read the event feed from its newest event on.
const newest = (await call("GET", "/v0/events?order=desc&limit=1")).data;
let since: string | undefined = newest[0]?.id;

// 5. Send a message.
const sent = await call(
  "POST",
  `/v0/inboxes/${box.id}/messages`,
  {
    to: [process.env.MY_EMAIL],
    subject: "Hello from MailCraft",
    text: "Reply to this email and the quickstart will answer.",
  },
  true,
);
console.log("sent:", sent.id);

// 3. Wait for your reply on the event feed (a webhook is the other way).
let received: { message_id: string; thread_id: string } | undefined;
const deadline = Date.now() + 600_000;
while (!received && Date.now() < deadline) {
  await new Promise((r) => setTimeout(r, 5000));
  const page = await call("GET", `/v0/events${since ? `?since=${since}` : ""}`);
  for (const event of page.data) {
    since = event.id;
    if (event.type === "message.received" && event.data.inbox_id === box.id) {
      received = event.data;
      break;
    }
  }
}
if (!received) throw new Error("No reply within 10 minutes.");

// 4. Read the thread and the message.
const thread = await call("GET", `/v0/threads/${received.thread_id}`);
const mail = await call("GET", `/v0/messages/${received.message_id}`);
console.log(thread.messages.length, "messages in the thread; you wrote:", mail.text);

// 6. Reply.
const answer = await call("POST", `/v0/messages/${received.message_id}/reply`, { text: "Thanks, on it." }, true);
console.log("replied:", answer.id);
