#!/usr/bin/env node

const SITE = "https://www.lakesidemantra.in";
const args = process.argv.slice(2);
const command = args[0] || "help";
const value = (flag) => { const index = args.indexOf(flag); return index >= 0 ? args[index + 1] : undefined; };

if (command === "help" || command === "--help") {
  console.log(`LakesideMantra CLI\n\nCommands:\n  docs\n  enquire --first NAME --last NAME --phone NUMBER --query TEXT [--email EMAIL]\n\nAn enquiry requires the traveller's consent and is not a confirmed booking.`);
  process.exit(0);
}
if (command === "docs") {
  console.log(`${SITE}/developers`);
  process.exit(0);
}
if (command !== "enquire") {
  console.error(JSON.stringify({ error: { code: "UNKNOWN_COMMAND", message: `Unknown command: ${command}`, hint: "Run with --help." } }));
  process.exit(2);
}

const payload = { firstName: value("--first"), lastName: value("--last"), phone: value("--phone"), query: value("--query"), email: value("--email") || "", source: "LakesideMantra CLI" };
const missing = ["firstName", "lastName", "phone", "query"].filter((field) => !payload[field]);
if (missing.length) {
  console.error(JSON.stringify({ error: { code: "VALIDATION_ERROR", message: "Required arguments are missing.", hint: "Provide --first, --last, --phone and --query.", details: { missingFields: missing } } }, null, 2));
  process.exit(2);
}

const response = await fetch(`${SITE}/api/v1/enquiries`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(payload) });
const body = await response.json().catch(() => ({ error: { code: "INVALID_RESPONSE", message: "The server did not return JSON." } }));
console.log(JSON.stringify(body, null, 2));
if (!response.ok) process.exit(1);
