const {
    withAndroidManifest,
    withDangerousMod,
    withGradleProperties,
} = require("@expo/config-plugins");
const fs = require("fs");
const path = require("path");

function withCustomAndroidConfig(config) {
    // Copy cert files
    config = withDangerousMod(config, [
        "android",
        async (config) => {
            const projectRoot = config.modRequest.projectRoot;
            const certSourceDir = path.join(projectRoot, "certFiles");
            const rawDestDir = path.join(
                projectRoot,
                "android/app/src/main/res/raw"
            );
            const xmlDestDir = path.join(
                projectRoot,
                "android/app/src/main/res/xml"
            );

            // Create directories if they don't exist
            if (!fs.existsSync(rawDestDir)) {
                fs.mkdirSync(rawDestDir, { recursive: true });
            }
            if (!fs.existsSync(xmlDestDir)) {
                fs.mkdirSync(xmlDestDir, { recursive: true });
            }

            // Copy your cert files
            if (fs.existsSync(path.join(certSourceDir, "raw"))) {
                fs.cpSync(path.join(certSourceDir, "raw"), rawDestDir, {
                    recursive: true,
                });
            }

            if (fs.existsSync(path.join(certSourceDir, "xml"))) {
                fs.cpSync(path.join(certSourceDir, "xml"), xmlDestDir, {
                    recursive: true,
                });
            }

            console.log("✅ Copied cert files to android/app/src/main/res");
            return config;
        },
    ]);

    // Modify AndroidManifest
    config = withAndroidManifest(config, (config) => {
        const mainApplication = config.modResults.manifest.application[0];

        // Add network security config if not already present
        if (!mainApplication.$["android:networkSecurityConfig"]) {
            mainApplication.$["android:networkSecurityConfig"] =
                "@xml/network_security_config";
        }

        console.log("✅ Modified AndroidManifest.xml");
        return config;
    });

    // Update gradle.properties for better performance
    config = withGradleProperties(config, (config) => {
        // Remove existing jvmargs if present
        config.modResults = config.modResults.filter(
            (item) =>
                !(item.type === "property" && item.key === "org.gradle.jvmargs")
        );

        // Add your custom jvmargs
        config.modResults.push(
            {
                type: "property",
                key: "org.gradle.jvmargs",
                value: "-Xmx16384m -XX:MaxMetaspaceSize=2024m",
            },
            {
                type: "property",
                key: "org.gradle.daemon",
                value: "false",
            }
        );

        console.log("✅ Updated gradle.properties with 16GB heap");
        return config;
    });

    return config;
}

module.exports = withCustomAndroidConfig;
