'use server';

import { headers } from 'next/headers';
import { prisma } from '@/lib/prisma';
import { upsertMailingListEntry } from '@/lib/mailingList';
import { verifyTurnstileToken } from '@/lib/turnstile';
import { getClientIp } from '@/lib/rateLimit';
import { getCurrentCustomer } from '@/lib/auth';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export async function subscribeToNewsletter(email: string, turnstileToken: string) {
  const trimmed = email.trim().toLowerCase();
  if (!EMAIL_RE.test(trimmed)) {
    return { ok: false, message: 'Enter a valid email address.' };
  }

  const ip = getClientIp(headers());
  const { success } = await verifyTurnstileToken(turnstileToken, ip);
  if (!success) {
    return { ok: false, message: 'CAPTCHA verification failed — please try again.' };
  }

  await prisma.newsletterSubscriber.upsert({
    where: { email: trimmed },
    create: { email: trimmed },
    update: {},
  });

  await upsertMailingListEntry({ email: trimmed, source: 'NEWSLETTER' });

  return { ok: true, message: "Thanks — you're on the list." };
}

export async function checkCustomerAuth() {
  const customer = await getCurrentCustomer();
  return { isAuthenticated: !!customer };
}
