import { isRecord } from "./utils";

export type DemoPasskeyView = {
  id: string;
  name: string;
  credentialID: string;
  createdAt?: string;
};

export type ListPasskeysResult =
  | {
      ok: true;
      passkeys: DemoPasskeyView[];
      status: number;
    }
  | {
      ok: false;
      status: number;
      message: string;
    };

export function parsePasskeyList(payload: unknown): DemoPasskeyView[] {
  if (!Array.isArray(payload)) return [];
  return payload
    .filter((entry): entry is Record<string, unknown> => isRecord(entry))
    .map((entry) => ({
      id: typeof entry.id === "string" ? entry.id : "",
      name: typeof entry.name === "string" ? entry.name : "Passkey",
      credentialID:
        typeof entry.credentialID === "string"
          ? entry.credentialID
          : typeof entry.credentialId === "string"
            ? entry.credentialId
            : "",
      createdAt: typeof entry.createdAt === "string" ? entry.createdAt : undefined,
    }))
    .filter((entry) => entry.id.length > 0);
}

export function buildPasskeyRenameDrafts(
  passkeys: DemoPasskeyView[],
  currentDrafts: Record<string, string>,
): Record<string, string> {
  const next: Record<string, string> = {};
  for (const passkey of passkeys) {
    next[passkey.id] = currentDrafts[passkey.id] ?? passkey.name;
  }
  return next;
}
