import { NativeModules, Platform } from 'react-native';
import type { EncryptionSession } from '@seald-io/sdk/lib/main.js';

const LINKING_ERROR =
  `The package 'react-native-seald-accelerator' doesn't seem to be linked. Make sure: \n\n` +
  Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
  '- You rebuilt the app after installing the package\n' +
  '- You are not using Expo managed workflow\n';

const SealdAccelerator = NativeModules.SealdAccelerator
  ? NativeModules.SealdAccelerator
  : new Proxy(
      {},
      {
        get() {
          throw new Error(LINKING_ERROR);
        },
      }
    );

const normalizeFilePath = (path: string) => (path.startsWith('file://') ? path.slice(7) : path); // iOS

export function encryptString(fileContent: string, filename: string, encryptionSession: EncryptionSession): Promise<string> {
  return SealdAccelerator.encryptFileAsString(fileContent, filename, encryptionSession.sessionId, encryptionSession._sessionSymKey.toB64());
}
export async function decryptString(fileContent: string, encryptionSession: EncryptionSession): Promise<string> {
  const clearFileData = await SealdAccelerator.decryptFileAsString(fileContent, encryptionSession._sessionSymKey.toB64());
  return JSON.parse(clearFileData)
}

export function encryptURI(fileURI: string, filename: string, encryptionSession: EncryptionSession): Promise<string> {
  return SealdAccelerator.encryptURI(normalizeFilePath(fileURI), filename, encryptionSession.sessionId, encryptionSession._sessionSymKey.toB64());
}
export async function decryptURI(fileURI: string, encryptionSession: EncryptionSession): Promise<{filename: string, messageId: string, path: string }> {
  const clearFileData = await  SealdAccelerator.decryptURI(normalizeFilePath(fileURI), encryptionSession._sessionSymKey.toB64());
  return JSON.parse(clearFileData)
}
