import { describe, it, expect, vi, beforeEach } from "vitest";
import { createRequest, createRouteContext, parseJsonResponse } from "@/__tests__/helpers/api-test-utils";
import { TEST_ROOM_DATA, TEST_RESTAURANT } from "@/__tests__/helpers/fixtures";

vi.mock("@/lib/prisma", () => ({ prisma: {} }));

vi.mock("@/lib/roomRepository", () => ({
  atomicUpdateRoom: vi.fn(),
}));

vi.mock("@/lib/roomEvents", () => ({
  notify: vi.fn(),
}));

import { POST } from "./route";
import { atomicUpdateRoom } from "@/lib/roomRepository";

const mockAtomicUpdate = vi.mocked(atomicUpdateRoom);

beforeEach(() => {
  vi.clearAllMocks();
});

describe("POST /api/room/[id]/undo", () => {
  it("undoes a like and decrements swipe count", async () => {
    mockAtomicUpdate.mockImplementation(async (_id, updater) => {
      const data = structuredClone(TEST_ROOM_DATA);
      data.likes[TEST_RESTAURANT.id] = ["user-1"];
      data.swipeCounts["user-1"] = 1;
      return updater(data);
    });

    const req = createRequest("/api/room/ROOM01/undo", {
      method: "POST",
      body: { userId: "user-1", restaurantId: TEST_RESTAURANT.id },
    });
    const ctx = createRouteContext({ id: "ROOM01" });
    const res = await POST(req, ctx);
    const { status, data } = await parseJsonResponse(res);

    expect(status).toBe(200);
    expect(data.ok).toBe(true);
  });

  it("clears match when undoing the matched restaurant", async () => {
    mockAtomicUpdate.mockImplementation(async (_id, updater) => {
      const data = structuredClone(TEST_ROOM_DATA);
      data.match = TEST_RESTAURANT.id;
      data.likes[TEST_RESTAURANT.id] = ["user-1", "user-2"];
      data.swipeCounts["user-1"] = 1;
      const result = updater(data);
      expect(result.match).toBeNull();
      return result;
    });

    const req = createRequest("/api/room/ROOM01/undo", {
      method: "POST",
      body: { userId: "user-1", restaurantId: TEST_RESTAURANT.id },
    });
    const ctx = createRouteContext({ id: "ROOM01" });
    await POST(req, ctx);
  });

  it("returns 403 when user is not a member", async () => {
    mockAtomicUpdate.mockImplementation(async (_id, updater) => {
      const data = structuredClone(TEST_ROOM_DATA);
      data.users = ["other-user"];
      return updater(data);
    });

    const req = createRequest("/api/room/ROOM01/undo", {
      method: "POST",
      body: { userId: "user-1", restaurantId: TEST_RESTAURANT.id },
    });
    const ctx = createRouteContext({ id: "ROOM01" });
    const res = await POST(req, ctx);
    expect(res.status).toBe(403);
  });

  it("returns 404 when room not found", async () => {
    mockAtomicUpdate.mockResolvedValue(null);

    const req = createRequest("/api/room/NONEXIST/undo", {
      method: "POST",
      body: { userId: "user-1", restaurantId: TEST_RESTAURANT.id },
    });
    const ctx = createRouteContext({ id: "NONEXIST" });
    const res = await POST(req, ctx);
    expect(res.status).toBe(404);
  });
});
