import { ConfigPlugin, withInfoPlist } from "@expo/config-plugins";
import { withDangerousMod, IOSConfig } from "@expo/config-plugins";
import { promises as fs } from "fs";
import type { Auth0PluginProps } from "./whitAuth0";

export const withAuth0IOS: ConfigPlugin<Auth0PluginProps> = (config) => {
  config = withAuth0InfoPlist(config);
  config = withAuth0AppDelegate(config);
  return config;
};

export const withAuth0InfoPlist: ConfigPlugin = (config) => {
  return withInfoPlist(config, async (config) => {
    if (!config.modResults.CFBundleIdentifier) {
      config.modResults.CFBundleIdentifier = "$(PRODUCT_BUNDLE_IDENTIFIER)";
    }
    if (!config.modResults.CFBundleURLTypes) {
      config.modResults.CFBundleURLTypes = [
        {
          CFBundleURLName: "auth0",
          CFBundleURLSchemes: ["$(PRODUCT_BUNDLE_IDENTIFIER)"],
        },
      ];
    }
    return config;
  });
};

export const withAuth0AppDelegate: ConfigPlugin = (config) => {
  return withDangerousMod(config, [
    "ios",
    async (config) => {
      const fileInfo = IOSConfig.Paths.getAppDelegate(
        config.modRequest.projectRoot
      );
      let contents = await fs.readFile(fileInfo.path, "utf-8");
      contents = modifyObjcAppDelegate({ contents });
      await fs.writeFile(fileInfo.path, contents);
      return config;
    },
  ]);
};

function modifyObjcAppDelegate({ contents }: { contents: string }): string {
  // Add import
  if (!contents.includes("#import <React/RCTLinkingManager.h>")) {
    // Replace the first line with the RCTLinkingManager import
    contents = contents.replace(
      /#import "AppDelegate.h"/g,
      `#import "AppDelegate.h"\n#import <React/RCTLinkingManager.h>`
    );
  }
  const initMethodInvocationBlock = `- (BOOL)application:(UIApplication *)app`;

  if (!contents.includes(initMethodInvocationBlock)) {
    // TODO: Determine if this is safe
    contents = contents.replace(
      /return YES;/g,
      `return YES;\n
}
- (BOOL)application:(UIApplication *)app
  openURL:(NSURL *)url
  options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  return [RCTLinkingManager application:app openURL:url options:options];
}
`
    );
  }

  return contents;
}
