import { Event } from 'nostr-tools'
import { Meta } from '../types'

/**
 * This function returns the signature of last signer
 * It will be used in the content of export signature's signedEvent
 */
const getLastSignersSig = (
  meta: Meta,
  signers: `npub1${string}`[]
): string | null => {
  // if there're no signers then use creator's signature
  if (signers.length === 0) {
    try {
      const createSignatureEvent: Event = JSON.parse(meta.createSignature)
      return createSignatureEvent.sig
    } catch (error) {
      return null
    }
  }

  // get last signer
  const lastSigner = signers[signers.length - 1]

  // get the signature of last signer
  try {
    const lastSignatureEvent: Event = JSON.parse(meta.docSignatures[lastSigner])
    return lastSignatureEvent.sig
  } catch (error) {
    return null
  }
}

/**
 * Checks if all signers have signed the sigit
 * @param signers - an array of npubs of all signers from the Sigit
 * @param signedBy - an array of npubs that have signed it already
 */
const isFullySigned = (
  signers: `npub1${string}`[],
  signedBy: `npub1${string}`[]
): boolean => {
  return signers.every((signer) => signedBy.includes(signer))
}

export { getLastSignersSig, isFullySigned }
