const express = require('express');
const path = require('path');
const fs = require('fs/promises');
const { randomUUID } = require('crypto');
const { sendToCrm } = require('./crm');

const app = express();
const PORT = process.env.MAIN_PORT || 4000;
const DATA_FILE = path.join(__dirname, 'data', 'submissions.json');

app.use(express.json());
app.use(express.static(__dirname));

const baseStore = { signups: [], contacts: [] };

async function ensureStore() {
  try {
    await fs.mkdir(path.dirname(DATA_FILE), { recursive: true });
    await fs.access(DATA_FILE);
  } catch (error) {
    await fs.writeFile(DATA_FILE, JSON.stringify(baseStore, null, 2));
  }
}

async function readStore() {
  try {
    const data = await fs.readFile(DATA_FILE, 'utf-8');
    const parsed = JSON.parse(data);
    return {
      signups: Array.isArray(parsed.signups) ? parsed.signups : [],
      contacts: Array.isArray(parsed.contacts) ? parsed.contacts : [],
    };
  } catch (error) {
    return { ...baseStore };
  }
}

async function appendSubmission(type, payload) {
  const current = await readStore();
  if (!Array.isArray(current[type])) current[type] = [];
  current[type].push(payload);
  await fs.writeFile(DATA_FILE, JSON.stringify(current, null, 2));
}

app.post('/api/signup', async (req, res) => {
  const { email, team, goal } = req.body || {};
  if (!email) {
    return res.status(400).json({ message: 'Email is required.' });
  }
  const submission = {
    id: randomUUID(),
    email: String(email).trim(),
    team: team || '',
    goal: goal || '',
    receivedAt: new Date().toISOString(),
  };
  await appendSubmission('signups', submission);
  await sendToCrm('signup', submission);
  res.json({ message: 'Signup received! Watch your inbox for routing instructions.' });
});

app.post('/api/contact', async (req, res) => {
  const { name, email, company, team, message } = req.body || {};
  if (!name || !email) {
    return res.status(400).json({ message: 'Name and email are required.' });
  }
  const submission = {
    id: randomUUID(),
    name: String(name).trim(),
    email: String(email).trim(),
    company: company || '',
    team: team || '',
    message: message || '',
    receivedAt: new Date().toISOString(),
  };
  await appendSubmission('contacts', submission);
  await sendToCrm('contact', submission);
  res.json({ message: 'Thanks! A LeadSniper specialist will reply from the main domain shortly.' });
});

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: Date.now() });
});

ensureStore().then(() => {
  app.listen(PORT, () => {
    console.log(`LeadSniper marketing site available at http://localhost:${PORT}`);
  });
});
