import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChartOfAccountsNotFoundError,
  ChartOfAccountsArchivedError,
  NameRequiredError,
} from "../lib/errors.generated";
import { baseDraftCoa, baseActiveCoa, baseArchivedCoa } from "../testing/fixtures";
import { run } from "./updateChartOfAccounts";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

const ctx: CommandContext = {
  actorId: "test-actor",
  permissions: ["coa-management:updateChartOfAccounts"],
};

describe("updateChartOfAccounts", () => {
  it("returns error when CoA does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent", name: "New Name" }, ctx);

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

  it("returns error when CoA is ARCHIVED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseArchivedCoa);

    const result = await run(db, { id: baseArchivedCoa.id, name: "New Name" }, ctx);

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

  it("returns error when name is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftCoa);

    const result = await run(db, { id: baseDraftCoa.id, name: "" }, ctx);

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

  it("updates name of a DRAFT CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCoa = { ...baseDraftCoa, name: "Updated Name" };
    spies.select.mockReturnValueOnce(baseDraftCoa);
    spies.update.mockReturnValue(updatedCoa);

    const result = await run(db, { id: baseDraftCoa.id, name: "Updated Name" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts.name).toBe("Updated Name");
    }
  });

  it("updates description of an ACTIVE CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCoa = { ...baseActiveCoa, description: "Updated description" };
    spies.select.mockReturnValueOnce(baseActiveCoa);
    spies.update.mockReturnValue(updatedCoa);

    const result = await run(db, { id: baseActiveCoa.id, description: "Updated description" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts.description).toBe("Updated description");
    }
  });

  it("clears description by setting to null", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCoa = { ...baseActiveCoa, description: null };
    spies.select.mockReturnValueOnce(baseActiveCoa);
    spies.update.mockReturnValue(updatedCoa);

    const result = await run(db, { id: baseActiveCoa.id, description: null }, ctx);

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

  it("passes custom fields through to update", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCoa = { ...baseDraftCoa, customField: "custom-value" };
    spies.select.mockReturnValueOnce(baseDraftCoa);
    spies.update.mockReturnValue(updatedCoa);

    const result = await run(
      db,
      { id: baseDraftCoa.id, name: "Updated", customField: "custom-value" } as UpdateInput,
      ctx,
    );

    expect(result.ok).toBe(true);
    // Verify set spy was called with custom fields
    expect(spies.set).toHaveBeenCalled();
    const setData = spies.set.mock.calls[0][0] as Record<string, unknown>;
    expect(setData.customField).toBe("custom-value");
  });
});

// Helper type for custom fields test
interface UpdateInput {
  id: string;
  name?: string;
  description?: string | null;
  customField: string;
  [key: string]: unknown;
}
