import template from "../templates/pb_schema.json";
import type { webVitalsIntegrationOptions } from "../types/web-vitals-integration-options.type";

export async function checkCollection(
  options: webVitalsIntegrationOptions,
  superuserToken?: string
): Promise<void> {
  // Ping the collection once
  const url = new URL(
    `/api/collections/${options.collectionName ?? "_webVitals"}/records`,
    options.url
  ).href;
  const pingRequest = await fetch(`${url}?perPage=1&skipTotal=true&fields=id`);

  if (pingRequest.status === 200 || pingRequest.status === 403) {
    // Collection exists (may not be public)
    return;
  }

  if (pingRequest.status !== 404) {
    // Some other error
    throw new Error(
      `Error while checking collection: ${pingRequest.status} ${pingRequest.statusText}`
    );
  }

  if (!superuserToken) {
    // Collection does not exist and cannot be created
    throw new Error(
      `Collection ${options.collectionName ?? "_webVitals"} does not exist and no valid superuser credentials provided to create it.`
    );
  }

  const templateData = template[0];
  if (options.collectionName) {
    templateData.name = options.collectionName;
  }
  // @ts-expect-error - Type is not optional
  delete templateData.id;
  for (const field of templateData.fields) {
    // @ts-expect-error - Type is not optional
    delete field.id;
  }

  // Collection does not exist, create it
  const collectionRequest = await fetch(
    new URL("/api/collections", options.url),
    {
      method: "POST",
      headers: {
        Authorization: superuserToken,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(templateData)
    }
  );
  if (collectionRequest.status !== 200) {
    throw new Error(
      `Error while creating collection: ${collectionRequest.status} ${collectionRequest.statusText}`
    );
  }
}
