import type { QRCodeDocument } from '@/types/DBDocumentTypes'
import { qrCodeDbLocal, qrCodeDbRemote } from '@/api/dbs'

const EPOHE = 1731661630981

export const createQrCodeDocument = async (
  qrCodeDocPartial: Pick<
    QRCodeDocument,
    | 'name'
    | 'placement'
    | 'actions'
    //| 'user_uuid'
    | 'predefinedMessages'
    | 'messageDeliveryMethod'
  >,
) => {
  const uri = Math.abs(Date.now() - EPOHE).toString(36)

  const qrCodeDoc: QRCodeDocument = {
    _id: `qr_code:${uri}`,
    type: 'qr_code',
    uri,
    url: `https://hereconnect.condev.ru/read/${uri}`,
    created_at: new Date().toISOString(),
    ...qrCodeDocPartial,
  }

  const { rev } = await qrCodeDbLocal.put(qrCodeDoc)
  qrCodeDoc._rev = rev

  const replicateResult = await qrCodeDbRemote.replicate.from(qrCodeDbLocal, {
    doc_ids: [qrCodeDoc._id],
  })

  // Проверяем результат репликации
  if (!replicateResult.ok) {
    throw new Error('Ошибка репликации: операция завершилась с ошибкой.')
  }
  if (replicateResult.doc_write_failures > 0) {
    throw new Error(`Ошибка записи документов: ${replicateResult.doc_write_failures}`)
  }
  if (replicateResult.errors.length > 0) {
    throw new Error(
      `Ошибки репликации: ${replicateResult.errors.map((e: { message: string }) => e.message).join(', ')}`,
    )
  }

  return qrCodeDoc
}

export const getQrCodeDocument = (uri: string) => {
  return qrCodeDbLocal.get<QRCodeDocument>(`qr_code:${uri}`).catch((error) => {
    if (error.name === 'not_found') {
      return qrCodeDbRemote.get<QRCodeDocument>(`qr_code:${uri}`)
    }
    throw error
  })
}
