/**
 * URL处理工具
 * 用于生成授权URL、解析URL参数等功能
 */

/**
 * 生成随机字符串
 * @param length 字符串长度，默认32位
 * @returns 随机字符串
 */
export function generateRandomString(length: number = 32): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

/**
 * 解析URL查询参数
 * @param url URL字符串，默认为当前URL
 * @returns 查询参数对象
 */
export function parseQueryParams(url: string = window.location.href): Record<string, string> {
  const params: Record<string, string> = {};
  const queryString = url.split('?')[1];
  if (!queryString) {
    return params;
  }

  const pairs = queryString.split('&');
  for (const pair of pairs) {
    const [key, value] = pair.split('=');
    if (key) {
      params[decodeURIComponent(key)] = decodeURIComponent(value || '');
    }
  }

  return params;
}

/**
 * 构建URL查询参数
 * @param params 查询参数对象
 * @returns 查询参数字符串
 */
export function buildQueryParams(params: Record<string, any>): string {
  const pairs: string[] = [];
  for (const [key, value] of Object.entries(params)) {
    if (value !== undefined && value !== null) {
      pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
    }
  }
  return pairs.length ? `?${pairs.join('&')}` : '';
}

/**
 * 生成OAuth2授权URL
 * @param authorizationEndpoint 授权端点URL
 * @param clientId 客户端ID
 * @param redirectUri 重定向URL
 * @param options 可选参数
 * @returns 授权URL
 */
export function generateAuthorizationUrl(
  authorizationEndpoint: string,
  clientId: string,
  redirectUri: string,
  options?: {
    responseType?: string;
    scope?: string;
    state?: string;
    [key: string]: any;
  }
): string {
  const {
    responseType = 'code',
    scope,
    state = generateRandomString(32),
    ...extraParams
  } = options || {};

  const params = {
    client_id: clientId,
    redirect_uri: redirectUri,
    response_type: responseType,
    state,
    ...(scope ? { scope } : {}),
    ...extraParams
  };

  const queryString = buildQueryParams(params);
  return `${authorizationEndpoint}${queryString}`;
}

/**
 * 检查当前URL是否为授权回调
 * @param url URL字符串，默认为当前URL
 * @returns 是否为授权回调
 */
export function isCallbackUrl(url: string = window.location.href): boolean {
  const params = parseQueryParams(url);
  return !!params.code || !!params.error;
}

/**
 * 获取当前URL的路径名
 * @param url URL字符串，默认为当前URL
 * @returns 路径名
 */
export function getPathname(url: string = window.location.href): string {
  const urlObj = new URL(url);
  return urlObj.pathname;
}

/**
 * 获取当前URL的主机名
 * @param url URL字符串，默认为当前URL
 * @returns 主机名
 */
export function getHostname(url: string = window.location.href): string {
  const urlObj = new URL(url);
  return urlObj.hostname;
}
