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

const mockSession = { user: { id: "user-1" } };

vi.mock("@/lib/api-auth", () => ({
  requireSessionOrApiKey: vi.fn(),
}));

const { mockPlanFindFirst, mockMemberFindFirst, mockMemberFindMany, mockUserFindFirst, mockInsertValues, mockInsertPlanValues, mockDeleteWhere } = vi.hoisted(() => ({
  mockPlanFindFirst: vi.fn(),
  mockMemberFindFirst: vi.fn(),
  mockMemberFindMany: vi.fn(),
  mockUserFindFirst: vi.fn(),
  mockInsertValues: vi.fn().mockResolvedValue(undefined),
  mockInsertPlanValues: vi.fn().mockResolvedValue(undefined),
  mockDeleteWhere: vi.fn().mockResolvedValue(undefined),
}));

vi.mock("@epicure/db", () => ({
  db: {
    query: {
      mealPlans: { findFirst: mockPlanFindFirst },
      mealPlanMembers: { findFirst: mockMemberFindFirst, findMany: mockMemberFindMany },
      users: { findFirst: mockUserFindFirst },
    },
    insert: vi.fn(() => ({ values: mockInsertValues })),
    delete: vi.fn(() => ({ where: mockDeleteWhere })),
  },
  mealPlans: { id: "id", userId: "user_id", weekStart: "week_start" },
  mealPlanMembers: { id: "id", mealPlanId: "meal_plan_id", userId: "user_id" },
  users: { id: "id", email: "email" },
  eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
  and: vi.fn((...args) => ({ args, op: "and" })),
}));

const { requireSessionOrApiKey } = await import("@/lib/api-auth");
import { GET, POST, DELETE } from "../route";

const ctx = { params: Promise.resolve({ weekStart: "2026-06-01" }) };

function makeRequest(method: string, body?: unknown, search = "") {
  return new NextRequest(`http://localhost/api/v1/meal-plans/2026-06-01/members${search}`, {
    method,
    headers: { "Content-Type": "application/json" },
    body: body ? JSON.stringify(body) : undefined,
  });
}

beforeEach(() => {
  vi.clearAllMocks();
  vi.mocked(requireSessionOrApiKey).mockResolvedValue({ session: mockSession as never, response: null });
});

describe("GET /api/v1/meal-plans/[weekStart]/members", () => {
  it("returns an empty list when the owner has no plan for this week yet", async () => {
    mockPlanFindFirst.mockResolvedValue(undefined);
    const res = await GET(makeRequest("GET"), ctx);
    expect(res.status).toBe(200);
    expect(await res.json()).toEqual([]);
  });

  it("returns members for an existing plan", async () => {
    mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
    mockMemberFindMany.mockResolvedValue([
      { id: "m1", userId: "user-2", role: "editor", createdAt: new Date(), user: { name: "Bob", username: null, avatarUrl: null } },
    ]);
    const res = await GET(makeRequest("GET"), ctx);
    const body = await res.json() as unknown[];
    expect(body).toHaveLength(1);
  });
});

describe("POST /api/v1/meal-plans/[weekStart]/members", () => {
  it("returns 400 on invalid body", async () => {
    const res = await POST(makeRequest("POST", { role: "viewer" }), ctx);
    expect(res.status).toBe(400);
  });

  it("returns 404 when the target user doesn't exist", async () => {
    mockUserFindFirst.mockResolvedValue(undefined);
    const res = await POST(makeRequest("POST", { email: "b@test.com", role: "viewer" }), ctx);
    expect(res.status).toBe(404);
  });

  it("returns 400 when inviting yourself", async () => {
    mockUserFindFirst.mockResolvedValue({ id: "user-1" });
    const res = await POST(makeRequest("POST", { email: "a@test.com", role: "viewer" }), ctx);
    expect(res.status).toBe(400);
  });

  it("auto-creates the plan for the week and invites the member", async () => {
    mockUserFindFirst.mockResolvedValue({ id: "user-2" });
    mockPlanFindFirst.mockResolvedValue(undefined); // no plan yet for this week
    mockMemberFindFirst.mockResolvedValue(undefined);
    const res = await POST(makeRequest("POST", { email: "b@test.com", role: "editor" }), ctx);
    expect(res.status).toBe(201);
    expect(mockInsertValues).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-1", weekStart: "2026-06-01" }));
    expect(mockInsertValues).toHaveBeenCalledWith(expect.objectContaining({ userId: "user-2", role: "editor" }));
  });

  it("returns 409 when already a member", async () => {
    mockUserFindFirst.mockResolvedValue({ id: "user-2" });
    mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1", weekStart: "2026-06-01" });
    mockMemberFindFirst.mockResolvedValue({ id: "existing" });
    const res = await POST(makeRequest("POST", { email: "b@test.com", role: "viewer" }), ctx);
    expect(res.status).toBe(409);
  });
});

describe("DELETE /api/v1/meal-plans/[weekStart]/members", () => {
  it("returns 400 when memberId is missing", async () => {
    const res = await DELETE(makeRequest("DELETE"), ctx);
    expect(res.status).toBe(400);
  });

  it("returns 404 when the owner has no plan for this week", async () => {
    mockPlanFindFirst.mockResolvedValue(undefined);
    const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
    expect(res.status).toBe(404);
  });

  it("returns 403 when caller is neither owner nor the member themselves", async () => {
    mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
    mockMemberFindFirst.mockResolvedValue({ id: "m1", userId: "user-2" });
    vi.mocked(requireSessionOrApiKey).mockResolvedValue({ session: { user: { id: "user-3" } } as never, response: null });
    const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
    expect(res.status).toBe(403);
  });

  it("allows the owner to remove a member", async () => {
    mockPlanFindFirst.mockResolvedValue({ id: "plan-1", userId: "user-1" });
    mockMemberFindFirst.mockResolvedValue({ id: "m1", userId: "user-2" });
    const res = await DELETE(makeRequest("DELETE", undefined, "?memberId=m1"), ctx);
    expect(res.status).toBe(204);
  });
});
