import type { AccountInput } from '../types'

export interface ParseResult {
  success: boolean
  data?: AccountInput[]
  error?: string
}

/**
 * Parse and validate JSON account data
 */
export function parseAccountJson(jsonString: string): ParseResult {
  try {
    const data = JSON.parse(jsonString)

    if (!Array.isArray(data)) {
      return {
        success: false,
        error: 'JSON 文件必须是数组格式',
      }
    }

    if (data.length === 0) {
      return {
        success: false,
        error: 'JSON 数组不能为空',
      }
    }

    // Validate each account
    const accounts: AccountInput[] = []
    for (let i = 0; i < data.length; i++) {
      const item = data[i]

      if (typeof item !== 'object' || item === null) {
        return {
          success: false,
          error: `第 ${i + 1} 条记录不是有效的对象`,
        }
      }

      if (!item.account || typeof item.account !== 'string') {
        return {
          success: false,
          error: `第 ${i + 1} 条记录缺少有效的 account 字段`,
        }
      }

      if (!item.password || typeof item.password !== 'string') {
        return {
          success: false,
          error: `第 ${i + 1} 条记录缺少有效的 password 字段`,
        }
      }

      if (!item.token || typeof item.token !== 'string') {
        return {
          success: false,
          error: `第 ${i + 1} 条记录缺少有效的 token 字段`,
        }
      }

      accounts.push({
        account: item.account,
        password: item.password,
        token: item.token,
      })
    }

    return {
      success: true,
      data: accounts,
    }
  } catch {
    return {
      success: false,
      error: 'JSON 解析失败，请检查文件格式',
    }
  }
}

/**
 * Validate email format
 */
export function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

/**
 * Validate token format (basic check)
 */
export function isValidToken(token: string): boolean {
  // Token should be a non-empty string with reasonable length
  return typeof token === 'string' && token.length >= 10
}
