import {
    ParsedDeploymentServiceConfig,
    ResponseObject,
    TCIGlobalConfig,
} from "@/src/types/turboci";
import bunGrabBulkSyncScripts from "@/src/utils/bun-grab-bulk-sync-script";
import serviceFlight from "@/src/utils/flight";
import grabGitRepoName from "@/src/utils/grab-git-repo-name";
import relayExecSSH from "@/src/utils/relay-exec-ssh";
import turboCIPkgrabDirNames from "@/src/utils/turboci-pkg-grab-dir-names";
import _ from "lodash";
import path from "path";

const { relayServerRsyncDir } = turboCIPkgrabDirNames();

type Params = {
    service: ParsedDeploymentServiceConfig;
    deployment: TCIGlobalConfig;
};

export default async function cronCheckServicesGit(
    params: Params,
): Promise<ResponseObject> {
    const { service, deployment } = params;

    if (!service.git || !service.servers?.[0]) {
        return { success: true };
    }

    const servers_private_ips = service.servers
        .map((srv) => srv.private_ip)
        .filter((ip) => Boolean(ip)) as string[];

    const git_array = Array.isArray(service.git) ? service.git : [service.git];

    for (let i = 0; i < git_array.length; i++) {
        const service_git = git_array[i];

        if (!service_git) continue;
        if (!service_git.keep_updated) continue;

        const git_url = service_git.repo_url;
        const repo_name = grabGitRepoName({ git_url });

        if (!repo_name) continue;

        console.log(`Checking Service \`${service.service_name}\` git ...`);

        const relay_dst = path.join(
            relayServerRsyncDir,
            service.service_name,
            "git",
            repo_name,
        );

        let git_pull_cmd = ``;

        git_pull_cmd += `cd ${relay_dst}\n`;
        git_pull_cmd += `git pull\n`;

        const git_pull_check = await relayExecSSH({
            cmd: git_pull_cmd,
            log_error: true,
        });

        if (git_pull_check?.match(/Already up to date./i)) {
            continue;
        }

        console.log(`Updating \`${service.service_name}\` git ...`);

        let cmd = ``;

        const src = relay_dst + "/";
        const dst = (service_git.work_dir || "/turboci/app") + "/";

        const sync_cmd = await relayExecSSH({
            cmd: bunGrabBulkSyncScripts({
                dst,
                src,
                private_server_ips: servers_private_ips,
                parrallel: true,
                relay_ignore: [".git"],
            }),
            bun: true,
            return_cmd_only: true,
        });

        cmd += `${sync_cmd}\n`;

        cmd += `echo "Git Setup Success!"\n`;

        const res = await relayExecSSH({
            cmd,
            log_error: true,
        });

        if (!res?.match(/Git Setup Success/)) {
            console.error(
                `\`${service.service_name}\` service git prep failed!`,
            );

            continue;
        }

        const restart = await serviceFlight({
            deployment,
            servers: service.servers,
            service,
        });

        if (restart) {
            console.log(
                `Service \`${service.service_name}\` new git version deployed successfully!`,
            );
        }
    }

    return {
        success: true,
    };
}
