import type { Device } from "@/lib/sitespeed";

import { db } from "@/lib/db";
import { siteTests } from "@/lib/db/schema";

const SITESPEED_API_URL = process.env.SITESPEED_API_URL || "https://speed.elevaseo.app";
const SITESPEED_API_KEY = process.env.SITESPEED_API_KEY || "";

export type LaunchTestArgs = {
  url: string;
  hostname: string;
  device: Device;
  siteId: string | null;
  /* Owning org. NULL only for anonymous audits triggered via the public
     integration API (no auth). All authenticated paths must pass an org. */
  organizationId: string | null;
  /* User who triggered the test. NULL for cron (no user) and anonymous
     audits. Set to user.id for manual user-triggered runs. */
  triggeredByUserId: string | null;
};

export type LaunchTestResult =
  | { ok: true; id: string; status: string }
  | { ok: false; status: number; error: string };

export async function launchSitespeedTest(args: LaunchTestArgs): Promise<LaunchTestResult> {
  const res = await fetch(`${SITESPEED_API_URL}/api/test`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${SITESPEED_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ url: args.url, device: args.device }),
  });
  if (!res.ok) {
    const data = await res.json().catch(() => ({}));
    return {
      ok: false,
      status: res.status,
      error: data.error || `Sitespeed API returned ${res.status}`,
    };
  }
  const { id, status } = await res.json();
  await db.insert(siteTests).values({
    id,
    siteId: args.siteId,
    organizationId: args.organizationId,
    triggeredByUserId: args.triggeredByUserId,
    hostname: args.hostname,
    url: args.url,
    device: args.device,
    status,
    createdAt: new Date().toISOString(),
  });
  return { ok: true, id, status };
}
