export interface TaskIssueEntry {
  id: string;
  text: string;
  showOnCard: boolean;
  occurredOn?: string | null;
}

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

function normalizeOccurredOn(raw: unknown): string | null {
  if (typeof raw !== 'string' || !raw.trim()) return null;
  const iso = raw.trim();
  if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) return null;
  return iso;
}

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,
      occurredOn: normalizeOccurredOn(row.occurredOn),
    });
  }
  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, occurredOn: null }];
}

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,
  };
}
