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 products API", () => {
  it("POST /api/admin/products creates product", async () => {
    prisma.product.create.mockResolvedValueOnce({ id: "p1" });
    const { POST } = await import("../../app/api/admin/products/route");

    const res = await POST(
      new Request("http://localhost/api/admin/products", {
        method: "POST",
        body: JSON.stringify({
          name: "Test",
          category: "Cat",
          shortDescription: "Short",
          description: "Desc",
          price: 10,
          stock: 1,
        }),
        headers: { "content-type": "application/json" },
      })
    );

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

  it("PUT /api/admin/products/[id] updates product", async () => {
    prisma.product.update.mockResolvedValueOnce({ id: "p1" });
    const { PUT } = await import("../../app/api/admin/products/[id]/route");

    const res = await PUT(
      new Request("http://localhost/api/admin/products/p1", {
        method: "PUT",
        body: JSON.stringify({
          name: "Test",
          category: "Cat",
          shortDescription: "Short",
          description: "Desc",
          price: 10,
          stock: 1,
        }),
        headers: { "content-type": "application/json" },
      }),
      { params: Promise.resolve({ id: "p1" }) }
    );

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

  it("DELETE /api/admin/products/[id] deletes product", async () => {
    prisma.product.delete.mockResolvedValueOnce({ id: "p1" });
    const { DELETE } = await import("../../app/api/admin/products/[id]/route");

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

    const data = await res.json();
    expect(data.success).toBe(true);
  });
});
