import { PrivateServerTtydParadigms, TtydInfoObject, User } from "@/src/types";
import {
    NormalizedServerObject,
    ParsedDeploymentServiceConfig,
} from "@/src/types/turboci";
import grabSSHPrefix from "@/src/utils/grab-ssh-prefix";
import grabTtydInfo from "./grab-ttyd-info";

type Params = {
    user: User;
    service?: Omit<ParsedDeploymentServiceConfig, "servers">;
    server?: NormalizedServerObject;
    paradigm: (typeof PrivateServerTtydParadigms)[number]["name"];
    cmd?: string;
};

export default async function grabTtydServerInfo({
    server,
    service,
    user,
    paradigm,
    cmd: passed_log_cmd,
}: Params): Promise<TtydInfoObject> {
    const first_log = service?.logs?.[0];
    const final_first_log =
        typeof first_log == "string" ? first_log : first_log?.cmd;

    const final_log = passed_log_cmd || final_first_log;

    if (paradigm == "logs" && !final_log) {
        throw new Error(
            `Service \`${service?.service_name}\` Doesn't have logs.`,
        );
    }

    let cmd = ``;

    cmd += ` ${grabSSHPrefix()}`;

    cmd += ` root@${server?.private_ip}`;

    if (paradigm == "logs" && final_log) {
        cmd += ` ${final_log}`;
    }

    return await grabTtydInfo({ cmd, user });
}
