const ADDRESS = "http://127.0.0.1:65000";

type Instance = {
  name: string;
  version: string;
  port: number;
  status: string;
};

class api {


} export default api;

export async function fetchInstanceList(): Promise<Instance[]> {
  const res = await fetch(`${ADDRESS}/instances/list`);
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Could not fetch instance list: ${message.trim()}`);
  }
  return res.json();
}

export async function fetchInstanceLogs(name: string): Promise<string[]> {
  const res = await fetch(`${ADDRESS}/instances/logs?name=${name}`);
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Could not fetch instance logs: ${message.trim()}`);
  }
  return res.json();
}

export async function sendStartInstanceRequest(name: string) {
  const res = await fetch(`${ADDRESS}/instances/start?name=${name}`, { method: "POST" });
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Start Instance Request failed: ${message.trim()}`);
  }
  return res.json;
}

export async function sendStopInstanceRequest(name: string) {
  const res = await fetch(`${ADDRESS}/instances/stop?name=${name}`, { method: "POST" });
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Stop Instance Request failed: ${message.trim()}`);
  }
  return res.json;
}

export async function sendCreateInstanceRequest(name: string, version: string, port: number) {
  const res = await fetch(`${ADDRESS}/instances/create?name=${name}&version=${version}&port=${port}`, { method: "POST" });
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Create instance request failed: ${message.trim()}`);
  }
  return res.json;
}

export async function sendDeleteInstanceRequest(name: string, purge: boolean) {
  const res = await fetch(`${ADDRESS}/instances/delete?name=${name}&purge=${purge}`, { method: "POST" });
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Delete instance request failed: ${message.trim()}`);
  }
  return res.json;
}

export async function sendModifyInstanceRequest(name: string, newName: string, newPort: number) {
  const res = await fetch(`${ADDRESS}/instances/modify?name=${name}&newName=${newName}&newPort=${newPort}`, { method: "POST" });
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Modify instance request failed: ${message.trim()}`);
  }
  return res.json;
}

export async function sendCommandRequest(name: string, payload: string) {
  const res = await fetch(`${ADDRESS}/instances/command?name=${name}`, { 
    method: "POST",
    body: JSON.stringify({ command: payload }),
    headers: { "Content-Type": "application/json" }, 
  });
  if (!res.ok) {
    const message = await res.text();
    throw new Error(`Send Instance Command failed: ${message.trim()}`);
  }
  return res.json;
}