import type { Goal } from "@paperclipai/shared"; function goalCreatedAt(goal: Goal) { const createdAt = goal.createdAt instanceof Date ? goal.createdAt : new Date(goal.createdAt); return Number.isNaN(createdAt.getTime()) ? 0 : createdAt.getTime(); } function pickEarliestGoal(goals: Goal[]) { return [...goals].sort((a, b) => goalCreatedAt(a) - goalCreatedAt(b))[0] ?? null; } export function selectDefaultCompanyGoalId(goals: Goal[]): string | null { const companyGoals = goals.filter((goal) => goal.level === "company"); const rootGoals = companyGoals.filter((goal) => !goal.parentId); const activeRootGoals = rootGoals.filter((goal) => goal.status === "active"); return ( pickEarliestGoal(activeRootGoals)?.id ?? pickEarliestGoal(rootGoals)?.id ?? pickEarliestGoal(companyGoals)?.id ?? null ); }