/**
 * NR Booth Referral Draw · Sheet endpoint for the code generator
 * ==============================================================
 * Receives codes POSTed by NR_Code_Generator.html and appends them,
 * deduplicated, to a CODES tab in the register spreadsheet.
 *
 * SETUP · three minutes, once
 * ---------------------------
 * 1. Open the register spreadsheet in Google Sheets.
 * 2. Extensions → Apps Script. Delete any placeholder code,
 *    paste this whole file, save.
 * 3. Deploy → New deployment → type: Web app.
 *      Execute as:      Me
 *      Who has access:  Anyone with the link
 *    Authorise when prompted (it only touches this spreadsheet).
 * 4. Copy the Web app URL (ends in /exec) and paste it into
 *    SHEET_ENDPOINT at the top of NR_Code_Generator.html.
 *
 * The URL is unguessable but treat it like a key: it accepts writes.
 * If it ever leaks, Deploy → Manage deployments → Archive kills it,
 * and a fresh deployment issues a new URL.
 *
 * WHAT IT DOES
 * ------------
 * Creates a CODES tab if missing (headers: Code · Added · Assigned?).
 * Appends only codes not already present anywhere in column A.
 * Returns {"added": n, "skipped": m} so the generator can toast the result.
 * Codes are validated server-side against the generator's alphabet:
 * anything malformed is silently dropped.
 */

var TAB = "CODES";
var VALID = /^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{7}$/;

function doPost(e) {
  var out = { added: 0, skipped: 0 };
  try {
    var body = JSON.parse(e.postData.contents || "{}");
    var incoming = (body.codes || [])
      .map(function (c) { return String(c).toUpperCase().trim(); })
      .filter(function (c) { return VALID.test(c); });

    var ss = SpreadsheetApp.getActive();
    var sh = ss.getSheetByName(TAB);
    if (!sh) {
      sh = ss.insertSheet(TAB);
      sh.getRange(1, 1, 1, 3).setValues([["Code", "Added", "Assigned?"]])
        .setFontWeight("bold");
      sh.setFrozenRows(1);
    }

    var last = sh.getLastRow();
    var existing = {};
    if (last > 1) {
      sh.getRange(2, 1, last - 1, 1).getValues().forEach(function (r) {
        if (r[0]) existing[String(r[0]).toUpperCase()] = true;
      });
    }

    var now = new Date();
    var rows = [];
    incoming.forEach(function (c) {
      if (existing[c]) { out.skipped++; return; }
      existing[c] = true;
      rows.push([c, now, "NO"]);
      out.added++;
    });
    if (rows.length) {
      sh.getRange(sh.getLastRow() + 1, 1, rows.length, 3).setValues(rows);
    }
  } catch (err) {
    out.error = String(err);
  }
  return ContentService.createTextOutput(JSON.stringify(out))
    .setMimeType(ContentService.MimeType.JSON);
}

/* GET requests get a health check, useful for testing the URL in a browser. */
function doGet() {
  return ContentService.createTextOutput(
    JSON.stringify({ ok: true, tab: TAB })
  ).setMimeType(ContentService.MimeType.JSON);
}
