import { promises as fs } from "node:fs";
import path from "node:path";

const MAILBOX_PATH = path.join(process.cwd(), ".productier-dev-mailbox.json");

async function readMailbox() {
  try {
    const raw = await fs.readFile(MAILBOX_PATH, "utf8");
    const entries = JSON.parse(raw);
    return Array.isArray(entries) ? entries : [];
  } catch (error) {
    if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
      return [];
    }
    throw error;
  }
}

export async function recordDevMail(entry) {
  const mailbox = await readMailbox();
  mailbox.unshift({
    id: crypto.randomUUID(),
    createdAt: new Date().toISOString(),
    ...entry
  });
  await fs.writeFile(MAILBOX_PATH, JSON.stringify(mailbox.slice(0, 25), null, 2));
}

export async function listDevMail(email) {
  const mailbox = await readMailbox();
  if (!email) {
    return mailbox;
  }
  return mailbox.filter(entry => entry.email.toLowerCase() === email.toLowerCase());
}
