import axios from "axios";
import { JSDOM } from 'jsdom';
import DOMPurify from "dompurify";

import { redis } from "./redis";
import { transporter } from "./mailer";
import { trimTooLong } from "./strings";
import { escape } from "validator";

export async function rateLimited(clientId: string) {
  const key = `contact:${clientId}`;
  const count = await redis.incr(key);
  if (count === 1) {
    await redis.expire(key, 600);
  }
  return count > 3;
}

export async function validateTurnstile(token: string, remoteip: string) {
  const body = new URLSearchParams({
    secret: process.env.CF_SECRET_KEY!,
    response: token,
    remoteip
  })

  const res = await axios.post("https://challenges.cloudflare.com/turnstile/v0/siteverify", body, {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  });

  const result = await res.data;
  return result.success === true;
}

export async function sendEmail(name: string, email: string, message: string) {
  const rawMessage = `From: ${name}\nEmail: ${email}\n\nMessage:\n${trimTooLong(message, 5000)}`;
  const messageHTML = sanitize(escape(rawMessage));

  console.log(process.env.SMTP_USER);
  console.log(process.env.SMTP_REPLY);
  console.log("Is it secure?:", process.env.SMTP_SECURE, typeof process.env.SMTP_SECURE, process.env.SMTP_SECURE == "true");

  await transporter.sendMail({
    from: `Nonszy Contact Form <${process.env.SMTP_USER}>`,
    replyTo: email,
    to: process.env.SMTP_REPLY,
    subject: `[CONTACT_FORM] from ${name}`,
    text: rawMessage,
    // html: messageHTML
  })
}

export function sanitize(dirty: string) {
  const window = new JSDOM('').window;
  return DOMPurify(window).sanitize(dirty);
}