// lib/utils.ts
import type { ClassValue } from 'clsx'
import clsx from 'clsx'
import { twMerge } from 'tailwind-merge'

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

const USER_ROLES_STORAGE_KEY = '__USER_ROLES__'

/**
 * 从路由获取 userRoles 并存储到 localStorage
 * @returns 返回获取到的 userRoles 数组
 */
function getQueryBeforeSecondQuestion(): string {
  try {
    const href = window.location.href || ''
    const firstQuestionIndex = href.indexOf('?')
    if (firstQuestionIndex === -1)
      return ''

    const queryCandidate = href.slice(firstQuestionIndex + 1)
    const secondQuestionIndex = queryCandidate.indexOf('?')
    const sliced = secondQuestionIndex === -1
      ? queryCandidate
      : queryCandidate.slice(0, secondQuestionIndex)

    // 兼容后端返回 `&&` 作为分隔符的情况，统一替换成单个 `&`
    return sliced.replace(/&{2,}/g, '&')
  }
  catch {
    return ''
  }
}

export function getUserRolesFromRouteAndStore(): string[] {
  try {
    const sanitizedSearch = getQueryBeforeSecondQuestion()
    const searchParams = new URLSearchParams(sanitizedSearch || window.location.search)
    const rolesFromRepeatedKeys = searchParams.getAll('userRoles').filter(Boolean)
    let userRoles: string[] = []

    if (rolesFromRepeatedKeys.length) {
      userRoles = Array.from(new Set(rolesFromRepeatedKeys))
    }
    else {
      const commaSeparated = searchParams.get('userRoles')
      if (commaSeparated) {
        const roles = commaSeparated
          .split(',')
          .map(role => role.trim())
          .filter(Boolean)
        if (roles.length) {
          userRoles = Array.from(new Set(roles))
        }
      }
    }

    // 如果获取到了 userRoles，存储到 localStorage
    if (userRoles.length > 0) {
      try {
        localStorage.setItem(USER_ROLES_STORAGE_KEY, JSON.stringify(userRoles))
      }
      catch (error) {
        console.error('存储 userRoles 到 localStorage 失败:', error)
      }
    }

    return userRoles
  }
  catch {
    return []
  }
}

/**
 * 从 localStorage 读取 userRoles
 * @returns 返回 userRoles 数组，如果没有则返回空数组
 */
export function getUserRolesFromStorage(): string[] {
  try {
    const stored = localStorage.getItem(USER_ROLES_STORAGE_KEY)
    if (stored) {
      const userRoles = JSON.parse(stored)
      if (Array.isArray(userRoles) && userRoles.length > 0) {
        return userRoles
      }
    }
  }
  catch (error) {
    console.error('从 localStorage 读取 userRoles 失败:', error)
  }
  return []
}

/**
 * 获取 userRoles（先同步路由到 localStorage，然后读取）
 * 这是推荐的统一方法，确保调用 fetchToolList 时能获取到正确的 userRoles
 * @returns 返回 userRoles 数组，如果没有则返回空数组
 */
export function getUserRolesForApi(): string[] {
  // 先同步路由中的 userRoles 到 localStorage（如果路由中有的话）
  getUserRolesFromRouteAndStore()
  // 然后从 localStorage 读取（localStorage.setItem 是同步的，所以可以立即读取）
  return getUserRolesFromStorage()
}
