import { isNative } from "../firebase";

export type KycDocumentType = "personal-id" | "business-license";

export async function uploadKycDocument(
  uid: string,
  localUri: string,
  docType: KycDocumentType
): Promise<string> {
  if (!uid || !localUri) {
    throw new Error("Missing uid or image uri");
  }

  const fileName = `${docType}_${uid}_${Date.now()}.jpg`;

  if (isNative) {
    let storageModule: any;
    try {
      console.log("[kycDocumentService] Using native Firebase Storage upload", {
        uid,
        localUri,
        docType,
      });
      storageModule = require("@react-native-firebase/storage").default;
    } catch (e) {
      console.error(
        "[kycDocumentService] @react-native-firebase/storage not available",
        e
      );
      throw new Error("Storage module not installed");
    }

    const path = `kyc-documents/${uid}/${fileName}`;
    console.log("[kycDocumentService] Upload path (native):", path);
    const ref = storageModule().ref(path);

    try {
      console.log(
        "[kycDocumentService] Calling putFile with localUri",
        localUri
      );
      await ref.putFile(localUri);
    } catch (error) {
      console.error("[kycDocumentService] Error during putFile", error);
      throw error;
    }

    try {
      console.log("[kycDocumentService] Fetching download URL for path", path);
      const downloadUrl = await ref.getDownloadURL();
      console.log("[kycDocumentService] getDownloadURL success", downloadUrl);
      return downloadUrl;
    } catch (error) {
      console.error("[kycDocumentService] Error during getDownloadURL", error);
      throw error;
    }
  }

  console.log("[kycDocumentService] Using web Firebase Storage upload", {
    uid,
    localUri,
    docType,
  });
  const { getStorage, ref, uploadBytes, getDownloadURL } = await import(
    "firebase/storage"
  );

  const storage = getStorage();
  const response = await fetch(localUri);
  const blob = await response.blob();
  const storageRefPath = `kyc-documents/${uid}/${fileName}`;
  console.log("[kycDocumentService] Upload path (web):", storageRefPath);
  const storageRef = ref(storage, storageRefPath);
  try {
    await uploadBytes(storageRef, blob);
  } catch (error) {
    console.error("[kycDocumentService] Error during uploadBytes", error);
    throw error;
  }
  try {
    const downloadUrl = await getDownloadURL(storageRef);
    console.log("[kycDocumentService] Web getDownloadURL success", downloadUrl);
    return downloadUrl;
  } catch (error) {
    console.error("[kycDocumentService] Error during getDownloadURL", error);
    throw error;
  }
}
