const express = require("express");
const db = require("../db/models");
const wrapAsync = require("../helpers").wrapAsync;
const { publicWorkspaceSettings } = require("../security/workspaceSettings");

const router = express.Router();
const CONSENT_POLICY_VERSION = "2026-07-22-v1";

router.get(
  "/site",
  wrapAsync(async (req, res) => {
    const settings = await db.workspace_settings.findByPk("default");
    res.status(200).send(publicWorkspaceSettings(settings || {}));
  }),
);

router.post(
  "/intake",
  wrapAsync(async (req, res) => {
    const data = req.body || {};
    const name = String(data.name || "").trim();
    const email = String(data.email || "").trim();

    if (!name) {
      res.status(400).send({ error: "name_required" });
      return;
    }

    if (!email) {
      res.status(400).send({ error: "email_required" });
      return;
    }

    const consentAiNotes = Boolean(data.consent_ai_notes);
    const lead = await db.intake_leads.create({
      name,
      email,
      company: data.company,
      role_title: data.role_title,
      package_name: data.package_name,
      preferred_time: data.preferred_time,
      goal: data.goal,
      challenge: data.challenge,
      desired_outcome: data.desired_outcome,
      source: data.source || "website",
      consent_ai_notes: consentAiNotes,
      consent_ai_notes_at: consentAiNotes ? new Date() : null,
      consent_policy_version: consentAiNotes ? CONSENT_POLICY_VERSION : null,
      status: "new",
    });

    res.status(200).send(lead);
  }),
);

module.exports = router;
