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

const { mockOptima, mockJson, mockError } = vi.hoisted(() => ({
  mockOptima: {
    procurement: {
      fetchLinkedItems: vi.fn(),
      linkItem: vi.fn(),
      unlinkItem: vi.fn(),
    },
  },
  mockJson: vi.fn((data, init?) => {
    return new Response(JSON.stringify(data), {
      status: init?.status ?? 200,
    });
  }),
  mockError: vi.fn((status: number, message: string) => {
    throw { status, body: { message } };
  }),
}));

vi.mock("$lib", () => ({ optima: mockOptima }));
vi.mock("@sveltejs/kit", () => ({ json: mockJson, error: mockError }));

import { GET, POST } from "./+server";

describe("/procurement/catalog/linked", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(console, "error").mockImplementation(() => {});
  });

  describe("GET", () => {
    it("throws 401 when no access token", async () => {
      const event = {
        locals: {},
        url: new URL("http://localhost/linked?id=item-1"),
      };
      await expect(GET(event as any)).rejects.toBeDefined();
    });

    it("throws 400 when id is missing", async () => {
      const event = {
        locals: { session: { accessToken: "tok" } },
        url: new URL("http://localhost/linked"),
      };
      await expect(GET(event as any)).rejects.toEqual(
        expect.objectContaining({ status: 400 }),
      );
    });

    it("fetches linked items", async () => {
      mockOptima.procurement.fetchLinkedItems.mockResolvedValueOnce({
        data: [{ id: "linked-1" }],
      });

      const event = {
        locals: { session: { accessToken: "tok" } },
        url: new URL("http://localhost/linked?id=item-1"),
      };

      await GET(event as any);

      expect(mockOptima.procurement.fetchLinkedItems).toHaveBeenCalledWith(
        "tok",
        "item-1",
      );
      expect(mockJson).toHaveBeenCalledWith({ data: [{ id: "linked-1" }] });
    });
  });

  describe("POST", () => {
    it("throws 401 when no access token", async () => {
      const event = {
        locals: {},
        request: {
          json: vi.fn().mockResolvedValue({
            action: "link",
            identifier: "a",
            targetId: "b",
          }),
        },
      };
      await expect(POST(event as any)).rejects.toBeDefined();
    });

    it("throws 400 when fields are missing", async () => {
      const event = {
        locals: { session: { accessToken: "tok" } },
        request: {
          json: vi.fn().mockResolvedValue({ action: "link" }),
        },
      };
      await expect(POST(event as any)).rejects.toEqual(
        expect.objectContaining({ status: 400 }),
      );
    });

    it("links items", async () => {
      mockOptima.procurement.linkItem.mockResolvedValueOnce({ ok: true });

      const event = {
        locals: { session: { accessToken: "tok" } },
        request: {
          json: vi.fn().mockResolvedValue({
            action: "link",
            identifier: "a",
            targetId: "b",
          }),
        },
      };

      await POST(event as any);

      expect(mockOptima.procurement.linkItem).toHaveBeenCalledWith(
        "tok",
        "a",
        "b",
      );
      expect(mockJson).toHaveBeenCalledWith({ ok: true });
    });

    it("unlinks items", async () => {
      mockOptima.procurement.unlinkItem.mockResolvedValueOnce({ ok: true });

      const event = {
        locals: { session: { accessToken: "tok" } },
        request: {
          json: vi.fn().mockResolvedValue({
            action: "unlink",
            identifier: "a",
            targetId: "b",
          }),
        },
      };

      await POST(event as any);

      expect(mockOptima.procurement.unlinkItem).toHaveBeenCalledWith(
        "tok",
        "a",
        "b",
      );
    });

    it("throws 400 for invalid action", async () => {
      const event = {
        locals: { session: { accessToken: "tok" } },
        request: {
          json: vi.fn().mockResolvedValue({
            action: "destroy",
            identifier: "a",
            targetId: "b",
          }),
        },
      };

      await expect(POST(event as any)).rejects.toEqual(
        expect.objectContaining({ status: 400 }),
      );
    });
  });
});
