import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseActiveAccount, baseDraftAccount } from "../testing/fixtures";
import { run } from "./listUnassignedAccounts";

describe("listUnassignedAccounts", () => {
  it("returns unassigned active accounts in a CoA", async () => {
    const unassignedAccount = { ...baseActiveAccount, accountGroupId: null };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([unassignedAccount]);

    const result = await run(db, { chartOfAccountsId: "coa-2" });

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

  it("excludes accounts that are assigned to a group", async () => {
    const { db, spies } = createMockDb<DB>();
    // Only unassigned accounts returned by the query
    spies.select.mockReturnValue([]);

    const result = await run(db, { chartOfAccountsId: "coa-2" });

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

  it("excludes DRAFT accounts", async () => {
    const { db, spies } = createMockDb<DB>();
    // Query filters status = ACTIVE, so DRAFT accounts excluded
    spies.select.mockReturnValue([]);

    const result = await run(db, { chartOfAccountsId: "coa-2" });

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

  it("excludes INACTIVE accounts", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(db, { chartOfAccountsId: "coa-2" });

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

  it("returns accounts sorted by code ascending", async () => {
    const account1 = {
      ...baseDraftAccount,
      status: "ACTIVE" as const,
      accountGroupId: null,
      code: "1100",
    };
    const account2 = {
      ...baseDraftAccount,
      id: "account-6",
      status: "ACTIVE" as const,
      accountGroupId: null,
      code: "1200",
    };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([account1, account2]);

    const result = await run(db, { chartOfAccountsId: "coa-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([account1, account2]);
    }
  });

  it("returns empty list when all active accounts are assigned", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(db, { chartOfAccountsId: "coa-2" });

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