import type { QuestionType } from "@/db/schema/form"; export type FormAnswerValue = string | string[]; export type FormAnswerPayload = { questionId: string; value: FormAnswerValue; imageCdnId?: string | null; }; export function decodeCheckboxAnswer(value: FormAnswerValue | undefined): string[] { if (Array.isArray(value)) { return value.filter((item): item is string => typeof item === "string"); } if (!value) { return []; } try { const parsed: unknown = JSON.parse(value); if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) { return parsed; } } catch { // Older checkbox answers were stored as comma-separated text. } return value.split(", ").filter(Boolean); } export function encodeAnswerValue(value: FormAnswerValue): string { return Array.isArray(value) ? JSON.stringify(value) : value; } export function formatStoredAnswer( value: string | undefined, questionType: QuestionType | string ): string { if (!value) { return ""; } return questionType === "checkbox" ? decodeCheckboxAnswer(value).join(", ") : value; } export function answerCellValue( value: string | undefined, questionType: QuestionType | string, imageCdnId?: string | null, ) { const text = formatStoredAnswer(value, questionType); const imageUrl = imageCdnId ? `/cdn/${imageCdnId}` : ""; if (text && imageUrl) return `${text}\n${imageUrl}`; return text || imageUrl; }