const RESULT_STORAGE_KEY = 'questionnaire_result';

export interface StoredResult {
  answers: string[];
  savedAt: string;
  profileId?: string;
  recordId?: string;
}

function resultKey(questionnaireId: string) {
  return `${RESULT_STORAGE_KEY}_${questionnaireId}`;
}

export function saveResult(
  questionnaireId: string,
  answers: string[],
  profileId?: string,
  recordId?: string,
) {
  try {
    const result: StoredResult = {
      answers,
      savedAt: new Date().toISOString(),
      profileId,
      recordId,
    };
    sessionStorage.setItem(resultKey(questionnaireId), JSON.stringify(result));
    return true;
  } catch (error) {
    console.error('Failed to save result:', error);
    return false;
  }
}

export function loadResult(questionnaireId: string): StoredResult | null {
  try {
    const raw = sessionStorage.getItem(resultKey(questionnaireId));
    if (!raw) {
      return null;
    }

    const parsed = JSON.parse(raw) as Partial<StoredResult>;
    return Array.isArray(parsed.answers) ? parsed as StoredResult : null;
  } catch (error) {
    console.error('Failed to load result:', error);
    return null;
  }
}
