import bcrypt from "bcryptjs"

export function validateIsraeliID(id: string): boolean {
  if (!/^\d{9}$/.test(id)) return false

  // Luhn algorithm for Israeli ID
  let sum = 0
  for (let i = 0; i < 9; i++) {
    let digit = Number.parseInt(id[i])
    if (i % 2 === 1) {
      digit *= 2
      if (digit > 9) digit -= 9
    }
    sum += digit
  }
  return sum % 10 === 0
}

export function generateValidIsraeliID(): string {
  // Generate 8 random digits
  let id = ""
  for (let i = 0; i < 8; i++) {
    id += Math.floor(Math.random() * 10).toString()
  }

  // Calculate the check digit using Luhn algorithm
  let sum = 0
  for (let i = 0; i < 8; i++) {
    let digit = Number.parseInt(id[i])
    if (i % 2 === 1) {
      digit *= 2
      if (digit > 9) digit -= 9
    }
    sum += digit
  }

  // Calculate check digit
  const checkDigit = (10 - (sum % 10)) % 10
  id += checkDigit.toString()

  return id
}

export async function generateUniqueIsraeliID(): Promise<string> {
  const { safeQuery } = await import("./database")

  let attempts = 0
  const maxAttempts = 100

  while (attempts < maxAttempts) {
    const newId = generateValidIsraeliID()

    // Check if this ID already exists
    const existingUsers = (await safeQuery("SELECT national_id FROM users WHERE national_id = ?", [newId])) as any[]

    if (existingUsers.length === 0) {
      return newId
    }

    attempts++
  }

  throw new Error("Unable to generate unique ID after maximum attempts")
}

export async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, 12)
}

export async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash)
}
