// Sample project built to show the approach - placeholder data
// Receives a Qualtrics web service / workflow POST and appends one row per response.
// Idempotent on ResponseId so retries never create duplicate rows.
const SHEET = 'Responses (raw)';
const FIELDS = ['ResponseId','participant_id','audience','wave','date',
  'Q1','Q2','Q3','Q4','Q5','Q6','Q7','Q8','Q9','Q10','Q11','Q12','Q13','Q14','Q15',
  'imp_health','imp_relationships','imp_work','imp_finances','imp_growth'];

function doPost(e) {
  const lock = LockService.getScriptLock(); lock.waitLock(20000);
  try {
    const data = JSON.parse(e.postData.contents);
    const sh = SpreadsheetApp.getActive().getSheetByName(SHEET);
    const ids = sh.getRange(5, 1, Math.max(sh.getLastRow() - 4, 1), 1).getValues().flat();
    if (ids.indexOf(data.ResponseId) !== -1) return out({status: 'duplicate', id: data.ResponseId});
    const missing = FIELDS.filter(f => data[f] === undefined || data[f] === '');
    sh.appendRow(FIELDS.map(f => data[f] === undefined ? '' : data[f]));
    return out({status: missing.length ? 'saved_with_gaps' : 'saved', missing: missing});
  } finally { lock.releaseLock(); }
}
function out(o) { return ContentService.createTextOutput(JSON.stringify(o)).setMimeType(ContentService.MimeType.JSON); }
