type Question = {
  questionId: string;
};

type GroupArray = {
  group_key: string;
  questions: Question[];
};

type GroupObject = {
  [key: string]: {
    questions: Question[];
  };
};

type Form = {
  groups: GroupArray[] | GroupObject;
};

type NaAnswerData = Record<string, any>;

const createNaAnswer = (questionId: string): NaAnswerData => ({
  [`${questionId}_observation`]: "",
  [`${questionId}_answer`]: "na",
  [`${questionId}_uri`]: "",
  [`${questionId}_actions`]: {
    question_id: questionId,
    body: "",
    close_immediately: "",
    field_target_date: "",
    field_critical_to_safety: "",
    field_issue_type: "",
    field_responsible_person: "",
  },
});

export const getNaAnswerData = (
  form: Form,
  selectedGroup: string[]
): NaAnswerData => {
  let naAnswerData: NaAnswerData = {};

  if (!form || !form.groups) return naAnswerData;

  if (Array.isArray(form.groups)) {
    // ✅ checklist case
    form.groups.forEach((group) => {
      if (!selectedGroup.includes(group.group_key)) {
        group.questions.forEach((q) => {
          naAnswerData = { ...naAnswerData, ...createNaAnswer(q.questionId) };
        });
      }
    });
  } else {
    // ✅ audit / inspection case
    Object.entries(form.groups).forEach(([key, value]) => {
      if (!selectedGroup.includes(key)) {
        value.questions.forEach((q) => {
          naAnswerData = { ...naAnswerData, ...createNaAnswer(q.questionId) };
        });
      }
    });
  }

  return naAnswerData;
};
