import type { Audit } from '../types';

// In dev mode (no WP), load audit from seed JSON directly.
// In production (WP), fetch from REST API.

import seedData from '../../../templates/seed-audits.json';

const config = window.noon_audit_config;

export async function fetchAudit(slug: string): Promise<Audit> {
  // If REST URL is available (WP context), use it.
  if (config.restUrl) {
    const res = await fetch(`${config.restUrl}/audits/${slug}`, {
      headers: { 'X-WP-Nonce': config.nonce },
    });

    if (!res.ok) {
      throw new Error(`Failed to fetch audit: ${res.statusText}`);
    }

    return res.json();
  }

  // Dev fallback — use seed data.
  const audit = (seedData as unknown as Audit[]).find((a) => a.slug === slug);
  if (!audit) {
    throw new Error(`Audit "${slug}" not found in seed data.`);
  }

  return audit;
}
