/**
 * Vitest test setup.
 *
 * Backend uses Nitro auto-imports (defineEventHandler, requireUser, etc.) which
 * are injected at build time via unimport. In unit tests we don't actually
 * boot Nitro; we test pure logic + DB-layer functions in isolation.
 *
 * For endpoint-handler tests we either:
 *   1. Test the underlying db/* function directly (preferred — easy to mock)
 *   2. Stub Nitro globals (defineEventHandler etc.) — see below
 *
 * Stubs intentionally minimal — when we need full request-cycle tests we'll
 * add supertest + nitro `.output/server` boot (see ops/TESTING_STATE.md §4).
 */
import { vi } from "vitest";

// ─── Nitro / h3 globals ─────────────────────────────────────────────────────
// These are injected at build time via Nitro's unimport. In tests we stub
// the most-used ones so endpoint files can be imported (or referenced) without
// crashing. Add more as test surface grows.
const g = globalThis as Record<string, unknown>;

if (typeof g.defineEventHandler === "undefined") {
  g.defineEventHandler = (handler: unknown) => handler;
}
if (typeof g.defineNitroPlugin === "undefined") {
  g.defineNitroPlugin = (handler: unknown) => handler;
}
if (typeof g.createError === "undefined") {
  g.createError = ({
    statusCode,
    message,
    data,
  }: {
    statusCode?: number;
    message?: string;
    data?: unknown;
  }) => {
    const err = new Error(message ?? "error") as Error & {
      statusCode?: number;
      data?: unknown;
    };
    err.statusCode = statusCode;
    err.data = data;
    return err;
  };
}
if (typeof g.readBody === "undefined") {
  g.readBody = vi.fn(async (event: { body?: unknown }) => event.body);
}
if (typeof g.getQuery === "undefined") {
  g.getQuery = vi.fn((event: { query?: unknown }) => event.query ?? {});
}
if (typeof g.getHeader === "undefined") {
  g.getHeader = vi.fn(() => undefined);
}
if (typeof g.setResponseStatus === "undefined") {
  g.setResponseStatus = vi.fn();
}
if (typeof g.setHeader === "undefined") {
  g.setHeader = vi.fn();
}
if (typeof g.useRuntimeConfig === "undefined") {
  g.useRuntimeConfig = vi.fn(() => ({
    public: { supabase: { url: "", key: "" } },
    supabase: { url: "", key: "" },
  }));
}
if (typeof g.usePrisma === "undefined") {
  // Tests should override per-test via vi.mock("../../server/utils/prisma")
  g.usePrisma = vi.fn(() => {
    throw new Error("usePrisma not mocked in this test");
  });
}
