import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { GetCurrencyInput } from "../../primitives/query/getCurrency";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  BankAccountNotFoundError,
  InvalidBankNameError,
  InvalidAccountHolderNameError,
  CurrencyNotFoundError,
  MissingAccountIdentifierError,
} from "../lib/errors.generated";
import {
  baseDefaultBankAccount,
  baseSecondBankAccount,
  baseDraftPartner,
  baseActivePartner,
  baseInactivePartner,
} from "../testing/fixtures";
import { run } from "./updatePartnerBankAccount";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("updatePartnerBankAccount", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["business-partner:updatePartnerBankAccount"],
  };

  const baseCurrency = {
    id: "currency-usd",
    code: "USD",
    name: "US Dollar",
    symbol: "$",
    decimalPlaces: 2,
    isActive: true,
    isBaseCurrency: true,
    createdAt: new Date("2024-01-01"),
    updatedAt: null,
  };

  const mockGetCurrency = (_db: unknown, input: GetCurrencyInput, _ctx: unknown) =>
    Promise.resolve({
      ok: true as const,
      value: {
        currency: "id" in input && input.id === "currency-usd" ? baseCurrency : null,
      },
    });
  const primitivesQueries = { getCurrency: mockGetCurrency };

  it("updates bank account details", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAccount = { ...baseDefaultBankAccount, bankName: "Updated Bank" };
    spies.select.mockReturnValueOnce(baseDefaultBankAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(
      db,
      { id: "bank-1", bankName: "Updated Bank" },
      ctx,
      primitivesQueries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.bankAccount.bankName).toBe("Updated Bank");
    }
  });

  it("updates routingNumber", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAccount = { ...baseDefaultBankAccount, routingNumber: "021000089" };
    spies.select.mockReturnValueOnce(baseDefaultBankAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(
      db,
      { id: "bank-1", routingNumber: "021000089" },
      ctx,
      primitivesQueries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.bankAccount.routingNumber).toBe("021000089");
    }
  });

  it("updates swiftBic", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAccount = { ...baseDefaultBankAccount, swiftBic: "BOFAUS3N" };
    spies.select.mockReturnValueOnce(baseDefaultBankAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(db, { id: "bank-1", swiftBic: "BOFAUS3N" }, ctx, primitivesQueries);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.bankAccount.swiftBic).toBe("BOFAUS3N");
    }
  });

  it("clears routingNumber when null is passed", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAccount = { ...baseDefaultBankAccount, routingNumber: null };
    spies.select.mockReturnValueOnce(baseDefaultBankAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(db, { id: "bank-1", routingNumber: null }, ctx, primitivesQueries);

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

  it("clears swiftBic when null is passed", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAccount = { ...baseSecondBankAccount, swiftBic: null };
    spies.select.mockReturnValueOnce(baseSecondBankAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(db, { id: "bank-2", swiftBic: null }, ctx, primitivesQueries);

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

  it("updates bank account for DRAFT partner", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const draftAccount = { ...baseDefaultBankAccount, partnerId: baseDraftPartner.id };
    const updatedAccount = { ...draftAccount, bankName: "Draft Bank" };
    spies.select.mockReturnValueOnce(draftAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(db, { id: "bank-1", bankName: "Draft Bank" }, ctx, primitivesQueries);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.bankAccount.bankName).toBe("Draft Bank");
    }
  });

  it("updates bank account for ACTIVE partner", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activeAccount = { ...baseDefaultBankAccount, partnerId: baseActivePartner.id };
    const updatedAccount = { ...activeAccount, bankName: "Active Bank" };
    spies.select.mockReturnValueOnce(activeAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(db, { id: "bank-1", bankName: "Active Bank" }, ctx, primitivesQueries);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.bankAccount.bankName).toBe("Active Bank");
    }
  });

  it("updates bank account for INACTIVE partner", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const inactiveAccount = { ...baseDefaultBankAccount, partnerId: baseInactivePartner.id };
    const updatedAccount = { ...inactiveAccount, bankName: "Inactive Bank" };
    spies.select.mockReturnValueOnce(inactiveAccount);
    spies.update.mockReturnValueOnce(updatedAccount);

    const result = await run(
      db,
      { id: "bank-1", bankName: "Inactive Bank" },
      ctx,
      primitivesQueries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.bankAccount.bankName).toBe("Inactive Bank");
    }
  });

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

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

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

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

    const result = await run(db, { id: "bank-1", bankName: "" }, ctx, primitivesQueries);

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

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

    const result = await run(db, { id: "bank-1", accountHolderName: "" }, ctx, primitivesQueries);

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

  it("returns error when currency not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDefaultBankAccount);

    const result = await run(
      db,
      { id: "bank-1", currencyId: "currency-nonexistent" },
      ctx,
      primitivesQueries,
    );

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

  it("returns error when update would remove all identifiers", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // Account has accountNumber but no iban
    spies.select.mockReturnValueOnce(baseDefaultBankAccount);

    const result = await run(
      db,
      { id: "bank-1", accountNumber: "", iban: "" },
      ctx,
      primitivesQueries,
    );

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