import { afterEach, describe, expect, it, vi } from "vitest";

import { GET as healthGet } from "@/app/api/health/route";
import { GET as defaultLocaleGet } from "@/app/api/site/default-locale/route";
import { setMaintenanceMode, updateSiteSettings, getSiteSettings } from "@/lib/app-config";
import { db } from "@/lib/db";

afterEach(() => {
  vi.restoreAllMocks();
});

describe("GET /api/health", () => {
  it("reports ok when the database responds", async () => {
    const response = await healthGet();
    expect(response.status).toBe(200);
    const body = await response.json();
    expect(body.status).toBe("ok");
    expect(body.checks.database).toBe("up");
    expect(typeof body.timestamp).toBe("string");
  });

  it("reports degraded (503) when the database query throws", async () => {
    vi.spyOn(db, "execute").mockRejectedValueOnce(new Error("db down"));
    const response = await healthGet();
    expect(response.status).toBe(503);
    const body = await response.json();
    expect(body.status).toBe("degraded");
    expect(body.checks.database).toBe("down");
  });
});

describe("GET /api/site/default-locale", () => {
  it("returns the runtime default locale and maintenance flag with no-store", async () => {
    const response = await defaultLocaleGet();
    expect(response.headers.get("Cache-Control")).toBe("no-store, max-age=0");
    const body = await response.json();
    expect(body.defaultLocale).toBe("de");
    expect(body.maintenanceEnabled).toBe(false);
  });

  it("reflects updated settings and maintenance state", async () => {
    const settings = await getSiteSettings();
    settings.defaultLocale = "ar";
    await updateSiteSettings(settings);
    await setMaintenanceMode(true);

    const response = await defaultLocaleGet();
    const body = await response.json();
    expect(body.defaultLocale).toBe("ar");
    expect(body.maintenanceEnabled).toBe(true);
  });
});
