import { generateShareToken } from './shareToken';

/** 账户若无 share_token 则自动生成并持久化 */
export async function ensureShareTokenForAccount(
  db: D1Database,
  id: string,
  existing: string | null,
): Promise<string> {
  if (existing) return existing;

  for (let attempt = 0; attempt < 6; attempt++) {
    const row = await db
      .prepare('SELECT share_token FROM totp_accounts WHERE id = ?')
      .bind(id)
      .first<{ share_token: string | null }>();
    if (row?.share_token) return row.share_token;

    const token = generateShareToken();
    try {
      await db
        .prepare('UPDATE totp_accounts SET share_token = ? WHERE id = ?')
        .bind(token, id)
        .run();
      return token;
    } catch {
      /* 唯一索引冲突时重试 */
    }
  }

  const final = await db
    .prepare('SELECT share_token FROM totp_accounts WHERE id = ?')
    .bind(id)
    .first<{ share_token: string | null }>();
  if (final?.share_token) return final.share_token;
  throw new Error('无法生成分享密钥');
}

export async function newShareTokenForInsert(db: D1Database): Promise<string> {
  for (let attempt = 0; attempt < 6; attempt++) {
    const token = generateShareToken();
    const dup = await db
      .prepare('SELECT id FROM totp_accounts WHERE share_token = ?')
      .bind(token)
      .first();
    if (!dup) return token;
  }
  throw new Error('无法生成分享密钥');
}
