import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { InvariantViolationMultipleOpenError } from "../lib/errors.generated";
import { pendingRequest } from "../testing/fixtures";
import { run } from "./getActiveApprovalRequest";

describe("getActiveApprovalRequest", () => {
  it("returns the open request when a PENDING request exists for the target", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([pendingRequest]);

    const result = await run(db, {
      targetEntityType: pendingRequest.targetEntityType,
      targetEntityId: pendingRequest.targetEntityId,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest).toEqual(pendingRequest);
    }
  });

  it("returns null when no request exists for the target", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(db, {
      targetEntityType: "Product",
      targetEntityId: "product-unknown",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest).toBeNull();
    }
  });

  it("returns null when only terminal requests exist for the target", async () => {
    const { db, spies } = createMockDb<DB>();
    // The status filter excludes terminal rows at the SQL level, so the
    // mocked select returns an empty array as the DB would.
    spies.select.mockReturnValue([]);

    const result = await run(db, {
      targetEntityType: "Product",
      targetEntityId: "product-300",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest).toBeNull();
    }
  });

  it("returns null when other targets have open requests but this target does not", async () => {
    const { db, spies } = createMockDb<DB>();
    // The targetEntityId filter narrows to this target, so the mocked
    // select returns an empty array as the DB would.
    spies.select.mockReturnValue([]);

    const result = await run(db, {
      targetEntityType: "Product",
      targetEntityId: "product-other",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest).toBeNull();
    }
  });

  it("raises INVARIANT_VIOLATION_MULTIPLE_OPEN when multiple non-terminal requests are found for the same target", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([pendingRequest, { ...pendingRequest, id: "request-pending-2" }]);

    const result = await run(db, {
      targetEntityType: pendingRequest.targetEntityType,
      targetEntityId: pendingRequest.targetEntityId,
    });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvariantViolationMultipleOpenError);
    }
  });
});
