import type { Metric } from "web-vitals";

const pathName = location.pathname.replace(/(?<=.)\/$/, "");
const hostName = location.hostname;

/**
 * Report web vitals metrics to PocketBase
 */
export function reportMetrics(
  metrics: Array<Metric>,
  baseUrl: string,
  batchEnabled: boolean
): void {
  // Check if metrics are available
  if (metrics.length === 0) {
    return;
  }

  const data = metrics.map((metric) => ({
    id: metric.id,
    hostName,
    pathName,
    metric: metric.name,
    score: metric.value,
    delta: metric.delta,
    rating: metric.rating,
    navigationType: metric.navigationType
  }));

  if (batchEnabled) {
    // Build bulk request payload
    const payload = data.map((metric) => ({
      // Use PUT method to upsert records
      method: "PUT",
      url: "/api/collections/_webVitals/records",
      body: metric
    }));

    // Send metrics to PocketBase
    void fetch(`${baseUrl}/api/batch`, {
      method: "POST",
      keepalive: true,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ requests: payload })
    });
  } else {
    for (const metric of data) {
      // Send metrics to PocketBase
      void fetch(`${baseUrl}/api/collections/_webVitals/records`, {
        method: "POST",
        keepalive: true,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(metric)
      });
    }
  }
}
