import { apiFetch } from "./auth";

export type GameServerStatus =
  | "DRAFT"
  | "PROVISIONING"
  | "INSTALLING"
  | "STOPPED"
  | "STARTING"
  | "RUNNING"
  | "STOPPING"
  | "ERROR"
  | "DELETING"
  | "DELETED";

export type SoftwareFamily =
  | "VANILLA"
  | "PAPER"
  | "PURPUR"
  | "FABRIC"
  | "FORGE"
  | "NEOFORGE"
  | "QUILT"
  | "BEDROCK_DEDICATED";

export interface Server {
  id: string;
  userId: string;
  planId: string | null;
  nodeId: string | null;
  name: string;
  status: GameServerStatus;
  version: number;
  edition: "JAVA" | "BEDROCK";
  softwareFamily: SoftwareFamily;
  minecraftVersion: string;
  eulaAccepted: boolean;
  hostPort: number | null;
  containerId: string | null;
  dataPath: string | null;
  ramMb: number;
  createdAt: string;
  updatedAt: string;
}

export interface ServerListResponse {
  servers: Server[];
}

export interface ServerActionResponse {
  server: Server;
  jobId?: string;
}

export interface CreateServerPayload {
  name: string;
  planId?: string;
  minecraftVersion: string;
  softwareFamily: SoftwareFamily;
  eulaAccepted: true;
}

export interface Plan {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  isFree: boolean;
  maxRamMb: number;
}

export interface PlanListResponse {
  plans: Plan[];
}

export async function listServers(): Promise<ServerListResponse> {
  return apiFetch<ServerListResponse>("/servers");
}

export async function getServer(id: string): Promise<Server> {
  return apiFetch<Server>(`/servers/${id}`);
}

export async function createServer(payload: CreateServerPayload): Promise<Server> {
  return apiFetch<Server>("/servers", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function startServer(id: string): Promise<ServerActionResponse> {
  return apiFetch<ServerActionResponse>(`/servers/${id}/start`, {
    method: "POST",
  });
}

export async function stopServer(id: string): Promise<ServerActionResponse> {
  return apiFetch<ServerActionResponse>(`/servers/${id}/stop`, {
    method: "POST",
  });
}

export async function listPlans(): Promise<PlanListResponse> {
  return apiFetch<PlanListResponse>("/plans");
}
