import type { WebPushSubscriptionDocument } from '@hereconnect/types'
import { publicSettingsDbRemote, webPushSubscriptionsDbRemote } from '@/api/dbs'
import { getUserUuid } from '@/utils/getUserUuid'
import { getBrowserUuid } from '@/utils/getBrowserUuid'

export const getWebPushSubscriptionDocument = async () => {
  const type = 'web_push_subscription'
  const user_uuid = getUserUuid()
  const browser_uuid = getBrowserUuid()
  const _id = `${type}:${user_uuid}:${browser_uuid}`
  return webPushSubscriptionsDbRemote.get(_id)
}

export const saveWebPushSubscription = async (subscription: PushSubscription) => {
  const type = 'web_push_subscription'
  const user_uuid = getUserUuid()
  const browser_uuid = getBrowserUuid()
  const _id = `${type}:${user_uuid}:${browser_uuid}`
  const created_at = new Date().toISOString()
  const webPushSubscriptionDoc: WebPushSubscriptionDocument<PushSubscriptionJSON> = {
    _id,
    type,
    user_uuid,
    browser_uuid,
    subscription: subscription.toJSON(),
    created_at,
  }
  try {
    const { rev } = await webPushSubscriptionsDbRemote.upsert(
      _id,
      (doc): WebPushSubscriptionDocument<PushSubscriptionJSON> | false => {
        webPushSubscriptionDoc._rev = doc._rev
        const isNotChanged =
          JSON.stringify(webPushSubscriptionDoc.subscription) === JSON.stringify(doc.subscription)
        if (isNotChanged) {
          return false
        }
        webPushSubscriptionDoc.created_at = doc.created_at ?? created_at
        webPushSubscriptionDoc.updated_at = doc.created_at ? new Date().toISOString() : created_at
        return webPushSubscriptionDoc
      },
    )
    webPushSubscriptionDoc._rev = rev
    console.log('Подписка успешно сохранена', webPushSubscriptionDoc)
    return webPushSubscriptionDoc
  } catch (error) {
    console.error('Ошибка сохранения подписки:', error)
    throw error
  }
}

export const getVapidPublicKey = async () => {
  const { value } = await publicSettingsDbRemote.get(
    'public_settings:message_delivery_method_web_push_vapid_public_key',
  )
  return value
}
