import { decodeRoutineStageDescription } from './routineMilestone';
import { parseMilestonePeriods, serializePeriodEntries } from './milestonePeriods';
import type { Milestone, MilestoneLink } from '../types';
import type { StageFormData } from '../components/detail/stageFormTypes';

export type { StageFormData };

export function parseMilestoneLinks(raw: string | null | undefined): MilestoneLink[] {
  if (!raw) return [];
  try {
    const parsed = JSON.parse(raw) as MilestoneLink[];
    return Array.isArray(parsed) ? parsed.filter((l) => l.url) : [];
  } catch {
    return [];
  }
}

export function buildStageFormState(
  milestone: Milestone | undefined,
  variant: 'project' | 'routine',
): StageFormData {
  const legacyOverview =
    variant === 'routine' ? decodeRoutineStageDescription(milestone?.description).overview : '';
  return {
    title: milestone?.title ?? '',
    subtitle: milestone?.subtitle?.trim() ?? legacyOverview,
    periodEntries: parseMilestonePeriods(milestone),
    progress: milestone?.progress ?? 0,
    links: parseMilestoneLinks(milestone?.links),
    pmMemberId: milestone?.pmMemberId ?? milestone?.pmMember?.id ?? '',
    assigneeMemberIds: milestone?.assigneeMembers?.map((m) => m.id) ?? [],
  };
}

export function stageFormToApiPayload(data: StageFormData, variant: 'project' | 'routine') {
  const base = {
    title: data.title.trim(),
    periodEntries: serializePeriodEntries(data.periodEntries),
    progress: data.progress,
    links: data.links,
  };
  if (variant === 'routine') {
    return {
      ...base,
      subtitle: data.subtitle.trim() || null,
      pmMemberId: data.pmMemberId || null,
      assigneeMemberIds: data.assigneeMemberIds,
    };
  }
  return base;
}
