import type { Task } from '../types';

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

export function newIssueEntry(text = ''): TaskIssueEntry {
  return {
    id: `issue-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
    text,
    showOnCard: true,
  };
}

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 : '';
    entries.push({
      id: typeof row.id === 'string' && row.id ? row.id : newIssueEntry().id,
      text,
      showOnCard: row.showOnCard !== false,
    });
  }
  return entries;
}

export function parseIssueEntries(task: Pick<Task, 'issueEntries' | 'issueNote' | 'showIssue'>): 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 getVisibleIssueEntries(task: Pick<Task, 'issueEntries' | 'issueNote' | 'showIssue'>): TaskIssueEntry[] {
  return parseIssueEntries(task).filter((entry) => entry.showOnCard && entry.text.trim());
}

export function hasVisibleIssue(task: Pick<Task, 'issueEntries' | 'issueNote' | 'showIssue'>): boolean {
  return getVisibleIssueEntries(task).length > 0;
}

export function getPrimaryIssueText(task: Pick<Task, 'issueEntries' | 'issueNote' | 'showIssue'>): string | null {
  const visible = getVisibleIssueEntries(task);
  if (visible.length > 0) return visible[visible.length - 1].text;
  return null;
}

export function serializeIssueEntries(entries: TaskIssueEntry[]): TaskIssueEntry[] {
  return entries
    .map((entry) => ({
      id: entry.id,
      text: entry.text.trim(),
      showOnCard: entry.showOnCard,
    }))
    .filter((entry) => entry.text.length > 0);
}
