import { beforeEach, describe, expect, it, vi } from "vitest";
import { prisma, __resetPrisma } from "../mocks/prisma";

const checkAdminAuth = vi.fn();
const authCheckPath = vi.hoisted(() => new URL("../../lib/auth-check.ts", import.meta.url).pathname);
const prismaPath = vi.hoisted(() => new URL("../../lib/prisma.ts", import.meta.url).pathname);
vi.mock(authCheckPath, () => ({ checkAdminAuth }));
vi.mock(prismaPath, () => ({ prisma }));

beforeEach(async () => {
  await vi.resetModules();
  __resetPrisma();
  checkAdminAuth.mockResolvedValue(null);
});

describe("Admin orders API", () => {
  it("GET /api/admin/orders returns orders", async () => {
    prisma.order.findMany.mockResolvedValueOnce([{ id: "o1" }]);
    prisma.order.count.mockResolvedValueOnce(1);
    const { GET } = await import("../../app/api/admin/orders/route");

    const res = await GET(new Request("http://localhost/api/admin/orders"));
    const data = await res.json();

    expect(data.total).toBe(1);
    expect(data.orders).toHaveLength(1);
  });

  it("GET /api/admin/orders/[id] returns 404 when missing", async () => {
    prisma.order.findUnique.mockResolvedValueOnce(null);
    const { GET } = await import("../../app/api/admin/orders/[id]/route");

    const res = await GET(new Request("http://localhost/api/admin/orders/o1"), {
      params: Promise.resolve({ id: "o1" }),
    });

    expect(res.status).toBe(404);
  });

  it("PUT /api/admin/orders/[id] updates order", async () => {
    prisma.order.findUnique.mockResolvedValueOnce({ id: "o1", status: "pending", items: [] });
    prisma.order.update.mockResolvedValueOnce({ id: "o1" });
    const { PUT } = await import("../../app/api/admin/orders/[id]/route");

    const res = await PUT(
      new Request("http://localhost/api/admin/orders/o1", {
        method: "PUT",
        body: JSON.stringify({ status: "pending" }),
        headers: { "content-type": "application/json" },
      }),
      { params: Promise.resolve({ id: "o1" }) }
    );

    expect(res.status).toBe(200);
  });
});
