'use server';

import { storeMail, updateMail } from '@/lib/logger/waitlistLogger';

const submissionTimestamps = new Map<string, number[]>();
const RATE_LIMIT_WINDOW = 60000;
const MAX_SUBMISSIONS = 3;

function isRateLimited(identifier: string): boolean {
  const now = Date.now();
  const timestamps = submissionTimestamps.get(identifier) || [];
  const recentTimestamps = timestamps.filter((t) => now - t < RATE_LIMIT_WINDOW);

  if (recentTimestamps.length >= MAX_SUBMISSIONS) {
    return true;
  }

  submissionTimestamps.set(identifier, [...recentTimestamps, now]);
  return false;
}

export async function submitEmail(email: string): Promise<{ success: boolean; error?: string }> {
  try {
    if (isRateLimited(email)) {
      console.warn('[WAITLIST] Rate limited:', email);
      return { success: false, error: 'Too many requests' };
    }

    await storeMail(email);
    console.log('[WAITLIST] Email stored:', email);
    return { success: true };
  } catch (error) {
    console.error('[WAITLIST] Failed to store email:', email, error);
    return { success: false, error: 'Failed to save' };
  }
}

export async function submitWaitlistData(
  email: string,
  data: { selected: string[]; other: string }
): Promise<{ success: boolean; error?: string }> {
  try {
    await updateMail(email, data);
    console.log('[WAITLIST] Data updated:', email, data.selected);
    return { success: true };
  } catch (error) {
    console.error('[WAITLIST] Failed to update data:', email, error);
    return { success: false, error: 'Failed to save' };
  }
}
