import { NextRequest } from "next/server";
import { beforeEach, describe, expect, it, vi } from "vitest";

const isDatabaseConfiguredMock = vi.fn();
const findManyMock = vi.fn();

vi.mock("../../lib/server/env", () => ({
  isDatabaseConfigured: () => isDatabaseConfiguredMock(),
}));

vi.mock("../../lib/server/db", () => ({
  prisma: {
    publishedRule: {
      findMany: (...args: unknown[]) => findManyMock(...args),
    },
  },
}));

import { GET } from "../../app/api/rules/route";

beforeEach(() => {
  isDatabaseConfiguredMock.mockReset();
  findManyMock.mockReset();
});

describe("GET /api/rules", () => {
  it("returns 503 when the database is not configured", async () => {
    isDatabaseConfiguredMock.mockReturnValue(false);
    const res = await GET(
      new NextRequest("https://x.test/api/rules"),
      undefined,
    );
    expect(res.status).toBe(503);
    expect(findManyMock).not.toHaveBeenCalled();
  });

  it("lists owned rules only", async () => {
    isDatabaseConfiguredMock.mockReturnValue(true);
    findManyMock.mockResolvedValueOnce([
      {
        id: "r1",
        title: "Owned",
        summary: null,
        createdAt: new Date("2026-01-01T00:00:00.000Z"),
        updatedAt: new Date("2026-01-02T00:00:00.000Z"),
      },
    ]);

    const res = await GET(
      new NextRequest("https://x.test/api/rules?limit=10"),
      undefined,
    );

    expect(res.status).toBe(200);
    expect(findManyMock).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { userId: { not: null } },
        take: 10,
      }),
    );
    const body = (await res.json()) as { rules: Array<{ id: string }> };
    expect(body.rules).toEqual([{ id: "r1", title: "Owned", summary: null, createdAt: expect.any(String), updatedAt: expect.any(String) }]);
  });
});
