import { join } from 'node:path';
import { existsSync, readFileSync, appendFileSync, mkdirSync } from 'node:fs';
import { createRouter } from '../../create-router';
import { DATA_PATH } from '../../data-path';

export const waitlistRouter = createRouter();

const WAITLIST_FILE = join(DATA_PATH, 'waitlist.txt');

waitlistRouter.post('/', async (ctx) => {
  const body = await ctx.req.json<{ email?: string }>();
  const email = body.email?.trim().toLowerCase();

  if (!email || !email.includes('@')) {
    return ctx.json({ error: 'Invalid email' }, 400);
  }

  const dir = DATA_PATH;
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true });
  }

  if (existsSync(WAITLIST_FILE)) {
    const existing = readFileSync(WAITLIST_FILE, 'utf-8');
    const emails = existing.split('\n').map((l) => l.trim().toLowerCase());
    if (emails.includes(email)) {
      return ctx.json({ ok: true });
    }
  }

  appendFileSync(WAITLIST_FILE, email + '\n', 'utf-8');
  return ctx.json({ ok: true });
});
