import PouchDB from '@/api/PouchDB'

import type {
  BaseDocument,
  QRCodeDocument,
  ChatDocument,
  MessageDocument,
  WebPushSubscriptionDocument,
  PublicSettingsDocument,
  UserChatSettingsDocument,
} from '@hereconnect/types'
import { DB_NAMES } from '@/constants/dbNames'

export const getRemoteDb = <T extends BaseDocument>(dbName: DB_NAMES) =>
  new PouchDB<T>(new URL(`${import.meta.env.VITE_API_URL}/${dbName}`, location.origin).toString(), {
    skip_setup: true,
  })

export const getLocalDb = <T extends BaseDocument>(dbName: DB_NAMES) => new PouchDB<T>(dbName)

export const qrCodeDbRemote = getRemoteDb<QRCodeDocument>(DB_NAMES.QR)
export const qrCodeDbLocal = getLocalDb<QRCodeDocument>(DB_NAMES.QR)
export const messagesDbLocal = getLocalDb<MessageDocument>(DB_NAMES.MESSAGES)
export const chatsDbLocal = getLocalDb<ChatDocument>(DB_NAMES.CHATS)
export const chatsDbRemote = getRemoteDb<ChatDocument>(DB_NAMES.CHATS)
export const webPushSubscriptionsDbRemote = getRemoteDb<
  WebPushSubscriptionDocument<PushSubscriptionJSON>
>(DB_NAMES.WEB_PUSH_SUBSCRIPTIONS)
export const publicSettingsDbRemote = getRemoteDb<PublicSettingsDocument>(DB_NAMES.PUBLIC_SETTINGS)
export const messagesDbRemote = getRemoteDb<MessageDocument>(DB_NAMES.MESSAGES)
export const userChatSettingsDbRemote = getRemoteDb<UserChatSettingsDocument>(
  DB_NAMES.USER_CHAT_SETTINGS,
)
