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("Work artifacts and delivery", () => {
  test("records exact idempotent artifact and delivery metadata", async () => {
    const t = convexTest({ modules, schema });
    const workId = 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,
      });
      return await ctx.db.insert("works", {
        createdAt: 1,
        objective: "Persist evidence",
        organizationId,
        projectId,
        status: "executing",
        title: "Artifact proof",
        updatedAt: 1,
      });
    });

    const draft = {
      idempotencyKey: "attempt-1:test-report",
      kind: "test-report" as const,
      metadataJson: "{}",
      producer: "fake-harness",
      provenanceJson: "{}",
      sourceRevision: "abc123",
      title: "Focused tests",
      verificationStatus: "verified" as const,
    };
    const first = await t.mutation(api.workArtifacts.recordArtifact, {
      draft,
      token: env.FLUE_DB_TOKEN,
      workId,
    });
    const replay = await t.mutation(api.workArtifacts.recordArtifact, {
      draft,
      token: env.FLUE_DB_TOKEN,
      workId,
    });
    expect(first.created).toBe(true);
    expect(replay).toEqual({ artifactId: first.artifactId, created: false });

    const delivery = await t.mutation(api.workArtifacts.recordDelivery, {
      artifactId: first.artifactId,
      draft: {
        externalId: "42",
        idempotencyKey: "pr:42",
        kind: "pull-request",
        metadataJson: "{}",
        provider: "gitea",
        sourceRevision: "abc123",
        status: "ready",
        target: "main",
        url: "https://git.example/pulls/42",
      },
      token: env.FLUE_DB_TOKEN,
      workId,
    });
    expect(delivery.created).toBe(true);
    const updated = await t.mutation(api.workArtifacts.updateDeliveryStatus, {
      deliveryId: delivery.deliveryId,
      metadataJson: '{"approvedBy":"user"}',
      status: "approved",
      token: env.FLUE_DB_TOKEN,
    });
    expect(updated).toEqual({ changed: true, status: "approved" });
    const stored = await t.run(async (ctx) => ({
      artifacts: await ctx.db.query("workArtifacts").collect(),
      deliveries: await ctx.db.query("workDeliveries").collect(),
      events: await ctx.db.query("workEvents").collect(),
    }));
    expect(stored.artifacts).toHaveLength(1);
    expect(stored.deliveries).toHaveLength(1);
    expect(stored.events.map((event) => event.kind)).toEqual([
      "artifact.recorded",
      "delivery.recorded",
      "delivery.updated",
    ]);
  });
});
