import { convexTest } from "convex-test";
import { describe, it, expect } from "vitest";
import { api } from "./_generated/api";
import schema from "./schema";

const modules = import.meta.glob("./**/*.ts");

describe("messages.submit", () => {
  it("creates one document with correct fields for valid payload", async () => {
    const t = convexTest(schema, modules);
    const messageId = await t.mutation(api.messages.submit, {
      fullName: "Jane Doe",
      email: "jane@example.com",
      topic: "support",
      message: "I need help with my order.",
    });
    expect(messageId).toBeTruthy();

    await t.run(async (ctx) => {
      const doc = await ctx.db.get(messageId);
      expect(doc).not.toBeNull();
      expect(doc!.fullName).toBe("Jane Doe");
      expect(doc!.email).toBe("jane@example.com");
      expect(doc!.topic).toBe("support");
      expect(doc!.message).toBe("I need help with my order.");
      expect(doc!.createdAt).toBeGreaterThan(0);
      expect(doc!.bookmarked).toBe(false);
    });
  });

  it("rejects invalid topic", async () => {
    const t = convexTest(schema, modules);
    await expect(
      t.mutation(api.messages.submit, {
        fullName: "Jane Doe",
        email: "jane@example.com",
        topic: "invalid_topic",
        message: "Hello",
      }),
    ).rejects.toThrow();
  });

  it("rejects missing required fields", async () => {
    const t = convexTest(schema, modules);
    const invalidArgs = {
      fullName: "Jane Doe",
    };
    await expect(
      t.mutation(api.messages.submit, invalidArgs as {
        fullName: string;
        email: string;
        topic: "products" | "orders" | "support" | "other";
        message: string;
      }),
    ).rejects.toThrow();
  });
});
