import { createRequire } from "node:module";
var __require = /* @__PURE__ */ createRequire(import.meta.url);

// src/libs/email/client.ts
import { createClient, Temv1alpha1 } from "@scaleway/sdk";
import { Logger } from "@contractspec/lib.logger";
var DEFAULT_FROM = {
  email: "noreply@transactional.contractspec.io",
  name: "ContractSpec"
};
var DEFAULT_TEAM_INBOX = {
  email: "contact@contractspec.io",
  name: "ContractSpec Team"
};
var DEFAULT_REGION = "fr-par";
var cachedConfig = null;
var cachedClient = null;
var apiFactory = (client) => new Temv1alpha1.API(client);
var mapRegion = (value) => {
  const normalized = value?.trim().toLowerCase();
  if (normalized === "par" || normalized === "fr-par")
    return "fr-par";
  if (normalized === "ams" || normalized === "nl-ams")
    return "nl-ams";
  if (normalized === "waw" || normalized === "pl-waw")
    return "pl-waw";
  return DEFAULT_REGION;
};
var getEmailConfig = () => {
  if (cachedConfig) {
    return { ok: true, config: cachedConfig };
  }
  const accessKey = process.env.SCALEWAY_ACCESS_KEY || process.env.SCALEWAY_ACCESS_KEY_QUEUE;
  const secretKey = process.env.SCALEWAY_SECRET_KEY || process.env.SCALEWAY_SECRET_KEY_QUEUE;
  const projectId = process.env.SCALEWAY_PROJECT_ID;
  if (!accessKey || !secretKey || !projectId) {
    return {
      ok: false,
      errorMessage: "Email service is not configured. Please contact us directly at contact@contractspec.io."
    };
  }
  const region = mapRegion(process.env.SCALEWAY_REGION);
  cachedConfig = {
    accessKey,
    secretKey,
    projectId,
    region,
    defaultZone: `${region}-1`,
    from: {
      email: process.env.SCALEWAY_EMAIL_FROM_EMAIL ?? DEFAULT_FROM.email,
      name: process.env.SCALEWAY_EMAIL_FROM_NAME ?? DEFAULT_FROM.name
    },
    teamInbox: {
      email: process.env.SCALEWAY_EMAIL_TEAM_EMAIL ?? DEFAULT_TEAM_INBOX.email,
      name: process.env.SCALEWAY_EMAIL_TEAM_NAME ?? DEFAULT_TEAM_INBOX.name
    }
  };
  return { ok: true, config: cachedConfig };
};
var getTemClient = (config) => {
  if (cachedClient) {
    return cachedClient;
  }
  const client = createClient({
    accessKey: config.accessKey,
    secretKey: config.secretKey,
    defaultProjectId: config.projectId,
    defaultRegion: config.region,
    defaultZone: config.defaultZone
  });
  cachedClient = apiFactory(client);
  return cachedClient;
};
var sendEmail = async (config, request) => {
  try {
    const client = getTemClient(config);
    await client.createEmail({
      region: config.region,
      projectId: config.projectId,
      from: config.from,
      to: request.to,
      subject: request.subject,
      text: request.text,
      html: request.html || request.text,
      additionalHeaders: request.replyTo ? [{ key: "Reply-To", value: request.replyTo }] : undefined
    });
    return { success: true };
  } catch (error) {
    new Logger().error("scaleway_tem_email_send_failed", {
      context: request.context ?? "email",
      error: error instanceof Error ? error.message : error
    });
    return {
      success: false,
      error,
      errorMessage: "Failed to send email via Scaleway."
    };
  }
};
var __internal = {
  resetCaches() {
    cachedClient = null;
    cachedConfig = null;
    apiFactory = (client) => new Temv1alpha1.API(client);
  },
  setApiFactory(factory) {
    apiFactory = factory;
  },
  setClient(client) {
    cachedClient = client;
  }
};

// src/libs/email/utils.ts
var escapeHtml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
var formatMultilineHtml = (value) => escapeHtml(value).replaceAll(`
`, "<br />");

// src/libs/email/waitlist.ts
"use server";
var WAITLIST_MISSING_CONFIG = "Waitlist service is not configured. Please try again later.";
var WAITLIST_SEND_ERROR = "Failed to join waitlist. Please try again later or contact us directly.";
var joinWaitlist = async (formData) => {
  const email = (formData.get("email") ?? "").toString().trim();
  if (!email || !email.includes("@")) {
    return {
      success: false,
      text: "Please enter a valid email address."
    };
  }
  const configResult = getEmailConfig();
  if (!configResult.ok || !configResult.config) {
    return {
      success: false,
      text: configResult.errorMessage ?? WAITLIST_MISSING_CONFIG
    };
  }
  const waitlistText = `
You're on the waitlist!

Thanks for joining the ContractSpec waitlist. You're now in line for early access to:

• Stabilize your AI-generated code with ContractSpec
• Multi-surface consistency (API, DB, UI, events)
• Safe regeneration without breaking changes
• AI governance and contract enforcement

We'll notify you as soon as early access is available. In the meantime, you can:

• Check out our docs: https://contractspec.io/docs
• Follow our progress on GitHub
• Book a demo call to see ContractSpec in action

We're excited to have you on board!

---
ContractSpec Team
https://contractspec.io

To remove yourself from the waitlist, reply to this email with "remove"
  `.trim();
  const waitlistHtml = `
    <div style="font-family: sans-serif; max-width: 640px; margin: 0 auto;">
      <h1 style="color: #8b5cf6;">You're on the waitlist!</h1>
      <p>Thanks for joining the ContractSpec waitlist. You're now in line for early access to:</p>
      <ul style="line-height: 1.8;">
        <li>Stabilize your AI-generated code with ContractSpec</li>
        <li>Multi-surface consistency (API, DB, UI, events)</li>
        <li>Safe regeneration without breaking changes</li>
        <li>AI governance and contract enforcement</li>
      </ul>
      <p>We'll notify you as soon as early access is available. In the meantime, you can:</p>
      <ul style="line-height: 1.8;">
        <li>Check out our <a href="https://contractspec.io/docs" style="color: #8b5cf6;">docs</a></li>
        <li>Follow our progress on GitHub</li>
        <li>Book a demo call to see ContractSpec in action</li>
      </ul>
      <p>We're excited to have you on board!</p>
      <hr style="margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;" />
      <p style="color: #6b7280; font-size: 14px;">
        ContractSpec Team<br />
        <a href="https://contractspec.io" style="color: #8b5cf6;">contractspec.io</a>
      </p>
      <p style="color: #9ca3af; font-size: 12px;">
        To remove yourself from the waitlist, reply to this email with "remove"
      </p>
    </div>
  `;
  const userSend = await sendEmail(configResult.config, {
    to: [{ email }],
    subject: "You're on the ContractSpec waitlist!",
    text: waitlistText,
    html: waitlistHtml,
    context: "waitlist-welcome"
  });
  if (!userSend.success) {
    return { success: false, text: WAITLIST_SEND_ERROR };
  }
  const teamNotificationText = `New waitlist signup from: ${email}`;
  const teamNotificationHtml = `
    <div style="font-family: sans-serif; max-width: 640px; margin: 0 auto;">
      <p style="margin: 0 0 8px;">New waitlist signup</p>
      <p style="margin: 0;"><strong>Email:</strong> ${formatMultilineHtml(email)}</p>
    </div>
  `;
  const teamSend = await sendEmail(configResult.config, {
    to: [configResult.config.teamInbox],
    subject: `New Waitlist Signup: ${email}`,
    text: teamNotificationText,
    html: teamNotificationHtml,
    context: "waitlist-team-notification"
  });
  if (!teamSend.success) {
    return { success: false, text: WAITLIST_SEND_ERROR };
  }
  return { success: true, text: "Successfully joined waitlist!" };
};
export {
  joinWaitlist
};
