import { cleanDoubleSlashes, withoutTrailingSlash } from 'ufo'
import {
  SmartCardApi,
  SignatureApi,
  Configuration,
  type VerifySignatureHashAlgorithmEnum,
  type VerifySignatureResponseDto,
  type SignPdfHashHashAlgorithmEnum
} from '~/.api-client-middleware'

export function useMiddlewareApi() {
  const appBaseUrl = useRuntimeConfig().app.baseURL
  const { serverApiBaseUrl, serverApiBasePath, clientProxyBasePath } = useRuntimeConfig().public
  const { jwt } = useAuth()

  const basePath = withoutTrailingSlash(
    cleanDoubleSlashes(import.meta.client ? appBaseUrl + clientProxyBasePath : serverApiBaseUrl + serverApiBasePath)
  )

  const smartCardApiClient = new SmartCardApi(
    new Configuration({ basePath, headers: { Authorization: jwt.value ? `Bearer ${jwt.value}` : '' } })
  )

  const signatureApiClient = new SignatureApi(
    new Configuration({ basePath, headers: { Authorization: jwt.value ? `Bearer ${jwt.value}` : '' } })
  )

  async function signPdfHash(document: Blob, certificateId: string, hashAlgorithm?: SignPdfHashHashAlgorithmEnum) {
    return signatureApiClient.signPdfHash({ document, certificateId, hashAlgorithm })
  }

  async function verifySignature(
    document: Blob,
    signature: string,
    certificateId?: string,
    hashAlgorithm?: VerifySignatureHashAlgorithmEnum
  ): Promise<VerifySignatureResponseDto> {
    return signatureApiClient.verifySignature({ document, signature, certificateId, hashAlgorithm })
  }

  return {
    signPdfHash,
    verifySignature
  }
}
