import Client from "./Client";

/**
 * Loads enum values from an OpenAPI schema for a given path, method, and field (e.g., category).
 *
 * @param path - API path, e.g., "/api/service-tickets/"
 * @param method - HTTP method
 * @param field - field name in parameters or request
 * @param schemaUrl - URL of the JSON schema, default "/api/schema/?format=json"
 * @returns Promise<Array<{ value: string; label: string }>>
 */
export async function fetchEnumFromSchemaJson(
  path: string,
  method: "get" | "post" | "patch" | "put",
  field: string,
  schemaUrl: string = "/schema/?format=json"
): Promise<Array<{ value: string; label: string }>> {
  try {
    const schema = await Client.public.get(schemaUrl);

    const methodDef = schema.paths?.[path]?.[method];
    if (!methodDef) {
      throw new Error(`Method ${method.toUpperCase()} for ${path} not found in schema.`);
    }

    // Search in "parameters" (e.g., GET query parameters)
    const param = methodDef.parameters?.find((p: any) => p.name === field);

    if (param?.schema?.enum) {
      return param.schema.enum.map((val: string) => ({
        value: val,
        label: val,
      }));
    }

    throw new Error(`Field '${field}' does not contain enum`);
  } catch (error) {
    console.error("Error loading enum values:", error);
    throw error;
  }
}
