// Server-side URL for screenshots/reports (direct to sitespeed API)
const SITESPEED_API_URL = process.env.SITESPEED_API_URL || "https://speed.elevaseo.app";

/* ─── Types ─── */

export type Device = "desktop" | "mobile";

export interface ResourceBreakdown {
  [type: string]: {
    count: number;
    transferSize: number;
    time: number;
  };
}

export interface TestMetrics {
  firstContentfulPaint: number;
  largestContentfulPaint: number;
  totalBlockingTime: number;
  cumulativeLayoutShift: number;
  timeToFirstByte: number;
  firstInputDelay: number;
  speedIndex: number;
  fullyLoaded: number;
  domContentLoaded: number;
  domInteractive: number;
  requests: number;
  transferSize: number;
  resourceBreakdown: ResourceBreakdown;
}

export interface LighthouseScores {
  performance: number;
  accessibility: number;
  "best-practices": number;
  seo: number;
}

export interface LighthouseOpportunity {
  id: string;
  title: string;
  description: string;
  savingsMs: number;
  savingsBytes: number;
  score: number;
}

export interface LighthouseDiagnostic {
  id: string;
  title: string;
  description: string;
  score: number;
  displayValue: string | null;
}

export interface LighthouseData {
  scores: LighthouseScores;
  opportunities: LighthouseOpportunity[];
  diagnostics: LighthouseDiagnostic[];
  reportUrl: string;
}

export interface TestScreenshots {
  afterPageCompleteCheck?: string;
  largestContentfulPaint?: string;
  layoutShift?: string;
}

export interface TestResult {
  id: string;
  url: string;
  browser: "chrome";
  device: Device;
  iterations: number;
  status: "queued" | "running" | "completed" | "failed";
  createdAt: string;
  completedAt: string | null;
  error: string | null;
  metrics: TestMetrics | null;
  lighthouse: LighthouseData | null;
  har: string | null;
  reportUrl: string | null;
  screenshots: TestScreenshots | null;
  // Live queue context — only populated by the worker while the job is
  // still waiting in line. Optional so older cached payloads stay
  // type-compatible.
  queuePosition?: number;
  queueLength?: number;
  estimatedWaitMs?: number;
}

export interface QueueStats {
  waiting: number;
  active: number;
  concurrency: number;
  avgDurationMs: number;
}

/* ─── Client-side API (proxied through Next.js) ─── */

export async function submitTest(
  url: string,
  opts?: { iterations?: number; browser?: string; device?: Device },
): Promise<{ id: string; status: string }> {
  const res = await fetch("/api/speed/test", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ url, ...opts }),
  });
  if (!res.ok) {
    const data = await res.json().catch(() => ({}));
    throw new Error(data.error || `Submit failed: ${res.status}`);
  }
  return res.json();
}

export async function getTest(id: string): Promise<TestResult> {
  const res = await fetch(`/api/speed/test/${id}`);
  if (!res.ok) throw new Error(`Fetch failed: ${res.status}`);
  return res.json();
}

export async function getTests(): Promise<TestResult[]> {
  const res = await fetch("/api/speed/tests");
  if (!res.ok) throw new Error(`Fetch failed: ${res.status}`);
  return res.json();
}

export function getResultUrl(path: string): string {
  return `${SITESPEED_API_URL}${path}`;
}

export function getScreenshotUrl(path: string): string {
  return `${SITESPEED_API_URL}${path}`;
}
