// Google Apps Script for surveyframe response collection
// Generated by surveyframe (export_google_sheet() or the SurveyBuilder)
// Target Google Sheet: {{SHEET_URL_COMMENT}}
//
// Setup:
// 1. Open the target Google Sheet
// 2. Go to Extensions > Apps Script
// 3. Paste this entire file, replacing any existing code
// 4. Click Deploy > New deployment > Web app
// 5. Set "Who has access" to "Anyone"
// 6. Copy the Web App URL and paste it into the SurveyBuilder
//    under Survey > Google Sheets Setup

const SHEET_NAME = "Responses";
const TARGET_SHEET_URL = {{TARGET_SHEET_URL}};
const EXPECTED_COLUMNS = {{EXPECTED_COLUMNS}};
const MAX_BODY_CHARS = 200000;

function doPost(e) {
  try {
    if (!e || !e.postData || !e.postData.contents) {
      throw new Error("Missing POST body.");
    }
    if (e.postData.contents.length > MAX_BODY_CHARS) {
      throw new Error("POST body too large.");
    }
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = ss.getSheetByName(SHEET_NAME);

    if (!sheet) {
      sheet = ss.insertSheet(SHEET_NAME);
      sheet.appendRow(EXPECTED_COLUMNS);
      sheet.getRange(1, 1, 1, EXPECTED_COLUMNS.length)
           .setFontWeight("bold")
           .setBackground("#1a1a2e")
           .setFontColor("#ffffff");
    }

    const data = JSON.parse(e.postData.contents);
    if (!data || Array.isArray(data) || typeof data !== "object") {
      throw new Error("POST body must be a JSON object.");
    }
    const row = EXPECTED_COLUMNS.map(col => data[col] !== undefined ? data[col] : "");
    sheet.appendRow(row);

    return ContentService
      .createTextOutput(JSON.stringify({ status: "ok", rows: sheet.getLastRow() - 1 }))
      .setMimeType(ContentService.MimeType.JSON);

  } catch (err) {
    return ContentService
      .createTextOutput(JSON.stringify({ status: "error", message: err.toString() }))
      .setMimeType(ContentService.MimeType.JSON);
  }
}

function doGet(e) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName(SHEET_NAME);
  if (!sheet) {
    return ContentService
      .createTextOutput(JSON.stringify({ status: "ok", rows: 0 }))
      .setMimeType(ContentService.MimeType.JSON);
  }
  const lastRow = sheet.getLastRow();
  return ContentService
    .createTextOutput(JSON.stringify({ status: "ok", rows: Math.max(0, lastRow - 1) }))
    .setMimeType(ContentService.MimeType.JSON);
}
