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("signalRouting", () => {
  test("creates one normalized Signal from admitted conversation evidence", async () => {
    const t = convexTest({ modules, schema });
    const organization = 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 turnId = await ctx.db.insert("conversationTurns", {
        clientRequestId: "request-1",
        conversationId,
        createdAt: 1,
        status: "processing",
      });
      const messageId = await ctx.db.insert("conversationMessages", {
        content: "Fix the deploy",
        conversationId,
        createdAt: 1,
        ordinal: 0,
        role: "user",
        turnId,
      });
      return { messageId, organizationId, projectId };
    });

    const result = await t.mutation(api.signalRouting.createSignal, {
      messageIds: [String(organization.messageId)],
      organizationId: organization.organizationId,
      problemStatement: {
        constraints: ["Keep production stable"],
        desiredOutcome: "Deploy succeeds",
        summary: "The deploy is failing",
        title: "Fix deploy",
      },
      processedByAgentInstanceId: String(organization.organizationId),
      projectId: organization.projectId,
      token: env.FLUE_DB_TOKEN,
    });

    const stored = await t.run(async (ctx) => ({
      constraints: await ctx.db.query("signalConstraints").collect(),
      signal: await ctx.db.get(result.signalId),
      sources: await ctx.db.query("signalSources").collect(),
    }));
    expect(stored.signal).toMatchObject({
      desiredOutcome: "Deploy succeeds",
      summary: "The deploy is failing",
      title: "Fix deploy",
    });
    expect(stored.constraints.map((row) => row.value)).toEqual([
      "Keep production stable",
    ]);
    expect(stored.sources[0]?.rawTextSnapshot).toBe("Fix the deploy");
  });
});
