import { appendFile, mkdir } from 'node:fs/promises';
import path from 'node:path';

export const LEAD_SOURCES = ['result', 'report', 'team-waitlist', 'workshop-waitlist'] as const;
export type LeadSource = (typeof LEAD_SOURCES)[number];

export interface Lead {
  email: string;
  source: LeadSource;
  resultCode?: string;
  consent: true;
  createdAt: string;
}

/** Swap for a real list (ConvertKit, Mailchimp, Brevo, a database…) without touching the routes. */
export interface LeadStore {
  save(lead: Lead): Promise<void>;
}

const fileStore: LeadStore = {
  async save(lead) {
    const dir = path.join(process.cwd(), 'data');
    await mkdir(dir, { recursive: true });
    await appendFile(path.join(dir, 'leads.jsonl'), JSON.stringify(lead) + '\n', 'utf8');
  },
};

const consoleStore: LeadStore = {
  async save(lead) {
    const [name, domain] = lead.email.split('@');
    console.info('[lead]', { ...lead, email: `${name.slice(0, 2)}***@${domain}` });
  },
};

/** Accepts sign-ups and keeps nothing: for building and testing without collecting real data. */
const noneStore: LeadStore = {
  async save() {},
};

export function getLeadStore(): LeadStore {
  const kind = process.env.LEAD_STORE ?? (process.env.NODE_ENV === 'production' ? 'console' : 'file');
  if (kind === 'none') return noneStore;
  return kind === 'file' ? fileStore : consoleStore;
}

export { isValidEmail } from './email';
