import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AccountNotFoundError,
  ChartOfAccountsArchivedError,
  InvalidStateTransitionError,
  OpenBalancesExistError,
  SuccessorNotActiveError,
} from "../lib/errors.generated";
import {
  baseActiveAccount,
  baseDraftAccount,
  baseInactiveAccount,
  baseActiveCoa,
  baseArchivedCoa,
} from "../testing/fixtures";
import { run } from "./deactivateAccount";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

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

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

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

  it("returns error when parent CoA is ARCHIVED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const accountInArchivedCoa = { ...baseActiveAccount, chartOfAccountsId: baseArchivedCoa.id };
    spies.select
      .mockReturnValueOnce(accountInArchivedCoa) // account lookup
      .mockReturnValueOnce(baseArchivedCoa); // CoA lookup

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

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

  it("returns error when account is not ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseInactiveAccount) // account lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup

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

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

  it("returns error when account is DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftAccount) // account lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup

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

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

  it("returns error when successor account is not ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveAccount) // account lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(baseDraftAccount); // successor lookup (DRAFT)

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

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

  it("deactivates an ACTIVE account without successor", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivated = { ...baseActiveAccount, status: "INACTIVE", successorAccountId: null };
    spies.select
      .mockReturnValueOnce(baseActiveAccount) // account lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup
    spies.update.mockReturnValue(deactivated);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.status).toBe("INACTIVE");
      expect(result.value.account.successorAccountId).toBeNull();
    }
  });

  it("deactivates an ACTIVE account with successor mapping", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const otherActiveAccount = { ...baseActiveAccount, id: "account-99" };
    const deactivated = {
      ...baseActiveAccount,
      status: "INACTIVE",
      successorAccountId: "account-99",
    };
    spies.select
      .mockReturnValueOnce(baseActiveAccount) // account lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(otherActiveAccount); // successor lookup
    spies.update.mockReturnValue(deactivated);

    const result = await run(
      db,
      {
        id: baseActiveAccount.id,
        successorAccountId: "account-99",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.status).toBe("INACTIVE");
      expect(result.value.account.successorAccountId).toBe("account-99");
    }
  });

  it("deactivates without balance check when GL hook is not registered", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivated = { ...baseActiveAccount, status: "INACTIVE" };
    spies.select.mockReturnValueOnce(baseActiveAccount).mockReturnValueOnce(baseActiveCoa);
    spies.update.mockReturnValue(deactivated);

    // No preDeactivationHook provided
    const result = await run(db, { id: baseActiveAccount.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.status).toBe("INACTIVE");
    }
  });

  it("returns error when GL hook reports open balances", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveAccount).mockReturnValueOnce(baseActiveCoa);

    const result = await run(
      db,
      {
        id: baseActiveAccount.id,
        preDeactivationHook: () => Promise.resolve(false),
      },
      ctx,
    );

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