import axios from "axios";
import type { Deployment } from "~/classes/Deployment";

export function getDeployments(namespace: string | undefined, onSuccess: (deployments: Deployment[]) => void)
{
    axios.get<Deployment[]>(ApiConfig.getHttpBase() + '/deployments', {
        headers: {
            Authorization: "Bearer " + requireToken()
        },
        params: getParams(namespace)
    })
    .then((response) => {
        onSuccess(response.data);
    })
    .catch();
}

export function rescaleDeployment(deployment: Deployment | undefined, replicaCount: number, onSuccess: () => void)
{
    if(deployment == null || deployment.metadata == null)
    {
        throw new Error("Deployment or metadata cannot be null");
    }
    if(deployment.metadata.name == null || deployment.metadata.namespace == null)
    {
        throw new Error("Name or namespace cannot be null");
    }
    axios.patch<Deployment[]>(ApiConfig.getHttpBase() + '/deployments/' + deployment.metadata.namespace + "/" + deployment.metadata.name, replicaCount, {
        headers: {
            Authorization: "Bearer " + requireToken(),
            "Content-Type": "text/plain"
        }
    })
    .then(() => {
        onSuccess();
    })
    .catch();
}

function getParams(namespace: string | undefined)
{
    if(namespace != undefined)
    {
        return {
            namespace: namespace
        }
    }
    return undefined;
}