export type ApexOnboardingRecordIds = {
  physicalId?: string;
  lifestyleId?: string;
  goalId?: string;
  conditionId?: string;
};

export type ApexOnboardingDraft<T = Record<string, unknown>> = {
  version: number;
  lastSavedAt?: string;
  completedAt?: string;
  form?: Partial<T>;
  recordIds?: ApexOnboardingRecordIds;
};

const APEX_ONBOARDING_VERSION = 1;

export function getApexOnboardingStorageKey(userId?: string | null) {
  return userId
    ? `apex-brain:onboarding:v${APEX_ONBOARDING_VERSION}:${userId}`
    : '';
}

export function readApexOnboardingDraft<
  T = Record<string, unknown>,
>(userId?: string | null): ApexOnboardingDraft<T> | null {
  if (typeof window === 'undefined' || !userId) {
    return null;
  }

  const storageKey = getApexOnboardingStorageKey(userId);

  try {
    const rawValue = window.localStorage.getItem(storageKey);

    if (!rawValue) {
      return null;
    }

    const parsedValue = JSON.parse(rawValue);

    if (!parsedValue || typeof parsedValue !== 'object') {
      return null;
    }

    return parsedValue as ApexOnboardingDraft<T>;
  } catch (error) {
    console.error('Failed to read APEX BRAIN onboarding draft:', error);
    return null;
  }
}

export function saveApexOnboardingDraft<T>(
  userId: string | null | undefined,
  draft: Omit<ApexOnboardingDraft<T>, 'version'>,
) {
  if (typeof window === 'undefined' || !userId) {
    return;
  }

  const storageKey = getApexOnboardingStorageKey(userId);
  const nextDraft: ApexOnboardingDraft<T> = {
    version: APEX_ONBOARDING_VERSION,
    ...draft,
    lastSavedAt: draft.lastSavedAt ?? new Date().toISOString(),
  };

  try {
    window.localStorage.setItem(storageKey, JSON.stringify(nextDraft));
  } catch (error) {
    console.error('Failed to save APEX BRAIN onboarding draft:', error);
  }
}

export function markApexOnboardingCompleted<T>(
  userId: string | null | undefined,
  draft: Omit<ApexOnboardingDraft<T>, 'version'>,
) {
  saveApexOnboardingDraft<T>(userId, {
    ...draft,
    completedAt: draft.completedAt ?? new Date().toISOString(),
  });
}

export function hasCompletedApexOnboarding(userId?: string | null) {
  const draft = readApexOnboardingDraft(userId);
  return Boolean(draft?.completedAt);
}
