import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { pendingRequest, revisionRequestedRequest } from "../testing/fixtures";
import { run } from "./listApprovalRequestsForRequester";

describe("listApprovalRequestsForRequester", () => {
  const userId = revisionRequestedRequest.requesterId;

  it("returns the requester's REVISION_REQUESTED requests by default", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([revisionRequestedRequest]);

    const result = await run(mock.db, { userId });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([revisionRequestedRequest]);
      expect(result.value.hasNextPage).toBe(false);
    }
    expect(mock.selects[0].sql).toMatch(/"requesterId"/i);
    expect(mock.selects[0].parameters).toContain(userId);
    expect(mock.selects[0].sql).toMatch(/"status"/i);
    expect(mock.selects[0].parameters).toContain("REVISION_REQUESTED");
  });

  it("accepts a non-default status (e.g. PENDING) to surface the requester's in-flight requests", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pendingRequest]);

    const result = await run(mock.db, { userId, status: "PENDING" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([pendingRequest]);
    }
    expect(mock.selects[0].sql).toMatch(/"status"/i);
    expect(mock.selects[0].parameters).toContain("PENDING");
  });

  it("returns an empty array when the user has no matching requests", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { userId });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("returns rows ordered by createdAt DESC", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([revisionRequestedRequest]);

    await run(mock.db, { userId });

    expect(mock.selects[0].sql).toMatch(/order by .*"createdAt" desc/i);
  });
});
