export interface TaskIssueEntry {
  id: string;
  text: string;
  showOnCard: boolean;
}

function newIssueId() {
  return `issue-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}

export function normalizeIssueEntries(raw: unknown): TaskIssueEntry[] {
  if (!Array.isArray(raw)) return [];
  const entries: TaskIssueEntry[] = [];
  for (const item of raw) {
    if (!item || typeof item !== 'object') continue;
    const row = item as Record<string, unknown>;
    const text = typeof row.text === 'string' ? row.text.trim() : '';
    if (!text) continue;
    entries.push({
      id: typeof row.id === 'string' && row.id ? row.id : newIssueId(),
      text,
      showOnCard: row.showOnCard !== false,
    });
  }
  return entries;
}

export function parseIssueEntriesFromTask(task: {
  issueEntries?: unknown;
  issueNote?: string | null;
  showIssue?: boolean;
}): TaskIssueEntry[] {
  const fromJson = normalizeIssueEntries(task.issueEntries);
  if (fromJson.length > 0) return fromJson;
  const legacy = task.issueNote?.trim();
  if (!legacy) return [];
  return [{ id: 'legacy', text: legacy, showOnCard: task.showIssue !== false }];
}

export function deriveIssueFields(entries: TaskIssueEntry[]) {
  const visible = entries.filter((entry) => entry.showOnCard && entry.text.trim());
  return {
    issueEntries: entries,
    issueNote: visible.length > 0 ? visible[visible.length - 1].text : null,
    showIssue: visible.length > 0,
  };
}
