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

describe("getAccount", () => {
  it("returns account when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveAccount]);

    const result = await run(mock.db, { id: baseActiveAccount.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account).toEqual(baseActiveAccount);
    }
    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain(baseActiveAccount.id);
    expect(mock.selects[0].sql).toMatch(/"id"/);
  });

  it("returns null when account not found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "nonexistent" });

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

  it("returns account when found by company-scoped code", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveAccount]);

    const result = await run(mock.db, { companyId: "company-1", code: "1200" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account).toEqual(baseActiveAccount);
    }
    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("company-1");
    expect(mock.selects[0].parameters).toContain("1200");
    expect(mock.selects[0].sql).toMatch(/"companyId"/);
    expect(mock.selects[0].sql).toMatch(/"code"/);
  });

  it("returns null when account not found by company-scoped code", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { companyId: "company-1", code: "9999" });

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