import { env } from "@code/env/convex";
import { convexTest } from "convex-test";
import { anyApi } from "convex/server";
import { describe, expect, test } from "vitest";

import schema from "./schema";

declare global {
  interface ImportMeta {
    readonly glob: (pattern: string) => Record<string, () => Promise<unknown>>;
  }
}

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

describe("works", () => {
  test("creates one proposed Work and one normalized attachment", async () => {
    const t = convexTest({ modules, schema });
    const fixture = await t.run(async (ctx) => {
      const organizationId = await ctx.db.insert("organizations", {
        createdAt: 1,
        createdBy: "user",
        kind: "personal",
        name: "Personal",
      });
      const projectId = await ctx.db.insert("projects", {
        createdAt: 1,
        name: "Zopu",
        normalizedSourceUrl: "https://example.com/zopu",
        organizationId,
        repositoryPath: "puter/zopu",
        sourceHost: "example.com",
        sourceUrl: "https://example.com/zopu",
        updatedAt: 1,
      });
      const conversationId = await ctx.db.insert("conversations", {
        createdAt: 1,
        organizationId,
      });
      const signalId = await ctx.db.insert("signals", {
        conversationId,
        createdAt: 1,
        desiredOutcome: "A working Slice 1",
        organizationId,
        processedByAgentInstanceId: String(organizationId),
        processedByAgentName: "zopu",
        projectId,
        sourceKey: "source-1",
        summary: "Slice 1 needs work",
        title: "Finish Slice 1",
      });
      return { organizationId, signalId };
    });

    const first = await t.mutation(api.works.createFromSignal, {
      organizationId: fixture.organizationId,
      signalId: fixture.signalId,
      token: env.FLUE_DB_TOKEN,
    });
    const second = await t.mutation(api.works.createFromSignal, {
      organizationId: fixture.organizationId,
      signalId: fixture.signalId,
      token: env.FLUE_DB_TOKEN,
    });
    expect(first.created).toBe(true);
    expect(second).toEqual({ created: false, workId: first.workId });
    const attachments = await t.run(async (ctx) =>
      ctx.db.query("signalWorkAttachments").collect()
    );
    expect(attachments).toHaveLength(1);
  });
});
