import config from '@/application/config'
import type { HttpResponse } from '@/application/types'
import type { BaseStorage } from '@/storage/baseStorage'

export function uuidv4() {
  return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (+c / 4)))).toString(16))
}

export function unduplicateArray(array: any[]) {
  return [...new Set(array.flat())]
}

export function getDomain() {
  // Check if not localhost
  if (window.location.hostname !== 'localhost') {
    return window.location.hostname
  }

  // Check if not IP address
  if (window.location.hostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
    return window.location.hostname
  }

  if (window.location.hostname.split('.').length < 3) {
    return window.location.hostname
  }

  return window.location.hostname.split('.').slice(-2).join('.')
}

export async function downloadCache<T extends { id: string; updatedAt: Date }>(endpoint: string, storage: BaseStorage<T>) {
  const request = await fetch(`${config.server_endpoint}/cache/${endpoint}`)
  const response = (await request.json()) as HttpResponse<T[]>

  if (!response.success) {
    console.error(`Failed to download ${endpoint}:`, response.message)
    return
  }

  const items = response.data ?? []

  for (const item of items) {
    let overwrite = false
    const existingItem = await storage.get(item.id)

    if (!existingItem || item.updatedAt > existingItem.updatedAt) {
      overwrite = true
    }

    await storage.add(item, overwrite)
  }
}
