const editableSessionFields = [
  "title",
  "session_at",
  "transcript_notes",
  "ai_summary",
  "key_topics",
  "goals_discussed",
  "blockers",
  "commitments",
  "homework",
  "emotional_themes",
  "important_quotes",
  "follow_up_email",
  "next_session_prep",
  "private_coach_notes",
  "shared_client_notes",
];

function editableSessionPayload(data) {
  const payload = {};

  for (const field of editableSessionFields) {
    if (Object.prototype.hasOwnProperty.call(data, field)) {
      payload[field] = data[field];
    }
  }

  return payload;
}

function draftChanges(session, data, userId) {
  return {
    ...editableSessionPayload(data),
    status: "draft",
    revision: Number(session.revision || 1) + 1,
    approved_at: null,
    approved_by_id: null,
    shared_at: null,
    shared_by_id: null,
    updatedById: userId,
  };
}

function approvalChanges(session, userId, now = new Date()) {
  if (!String(session.shared_client_notes || "").trim()) {
    const error = new Error("Shared client notes are required before approval");
    error.code = 400;
    throw error;
  }

  return {
    status: "approved",
    approved_at: now,
    approved_by_id: userId,
    updatedById: userId,
  };
}

function shareChanges(session, userId, now = new Date()) {
  if (session.status !== "approved") {
    const error = new Error("Session must be approved before sharing");
    error.code = 409;
    throw error;
  }

  return {
    status: "shared",
    shared_at: now,
    shared_by_id: userId,
    unshared_at: null,
    unshared_by_id: null,
    updatedById: userId,
  };
}

function unshareChanges(userId, now = new Date()) {
  return {
    status: "unshared",
    unshared_at: now,
    unshared_by_id: userId,
    updatedById: userId,
  };
}

module.exports = {
  editableSessionPayload,
  draftChanges,
  approvalChanges,
  shareChanges,
  unshareChanges,
};
