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

const mocks = vi.hoisted(() => ({ from: vi.fn(), call: vi.fn() }));
vi.mock("@/integrations/supabase/client.server", () => ({ supabaseAdmin: { from: mocks.from } }));
vi.mock("@tanstack/react-start/server", () => ({ getRequest: () => new Request("http://localhost:8080") }));
vi.mock("@/lib/ai/responses.server", () => ({ createResponsesCall: mocks.call }));
import { draftContactReply } from "@/lib/contact-replies.server";

function row(data: unknown) {
  const chain: Record<string, unknown> = {};
  for (const method of ["update", "eq", "select", "upsert"]) chain[method] = vi.fn(() => chain);
  chain['maybeSingle'] = vi.fn(async () => ({ data, error: null }));
  chain['then'] = (resolve: (value: unknown) => unknown) => Promise.resolve({ error: null }).then(resolve);
  return chain;
}

describe("Private contact reply drafts", () => {
  beforeEach(() => { vi.clearAllMocks(); vi.stubEnv("LOVABLE_API_KEY", "test-only"); });
  it("stores the suggested reply for review without returning it to the visitor", async () => {
    const saved = row(null);
    mocks.from.mockReturnValueOnce(row({ id: "contact", name: "Father", message: "Please help." }))
      .mockReturnValueOnce(row(null)).mockReturnValueOnce(saved);
    mocks.call.mockReturnValue({ result: { fullStream: (async function* () {
      yield { type: "text-delta", text: "Suggested reply for review" };
      yield { type: "finish", finishReason: "stop" };
    })() } });
    expect(await draftContactReply("contact")).toBeUndefined();
    expect(saved['update']).toHaveBeenCalledWith(expect.objectContaining({ suggested_reply: "Suggested reply for review", reply_status: "ready" }));
    expect(mocks.call).toHaveBeenCalledTimes(1);
  });
  it("does not regenerate a draft when the submission has already been claimed", async () => {
    mocks.from.mockReturnValueOnce(row(null));
    await draftContactReply("contact");
    expect(mocks.call).not.toHaveBeenCalled();
  });
  it("keeps new drafts paused without calling AI when the shared pause is active", async () => {
    const saved = row(null);
    mocks.from.mockReturnValueOnce(row({ id: "contact", name: "Father", message: "Help" }))
      .mockReturnValueOnce(row({ paused: true, pause_reason: "AI credits required" })).mockReturnValueOnce(saved);
    await draftContactReply("contact");
    expect(mocks.call).not.toHaveBeenCalled();
    expect(saved['update']).toHaveBeenCalledWith({ reply_status: "paused", reply_error: "AI credits required" });
  });
});