import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidPeriodStatusError,
  AccountNotFoundError,
  AccountNotActiveError,
  InvalidAmountError,
  CompanyMismatchError,
} from "../lib/errors.generated";
import {
  baseAccountingPeriod,
  neverOpenedPeriod,
  closedPeriod,
  baseAccount,
  baseAccount2,
  inactiveAccount,
  baseCompany,
  baseJournalEntry,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./processInventoryHandoff";

describe("processInventoryHandoff", () => {
  const baseInput = {
    companyId: baseCompany.id,
    accountingPeriodId: baseAccountingPeriod.id,
    sourceDocumentReference: "INV-ADJ-001",
    entryDate: new Date("2024-01-15"),
    debitAccountId: baseAccount.id,
    creditAccountId: baseAccount2.id,
    amount: 1000,
  };

  it("returns existing entry for idempotent duplicate", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const existingEntry = { ...baseJournalEntry, sourceDocumentReference: "INV-ADJ-001" };
    spies.select.mockReturnValueOnce(existingEntry);

    const result = await run(db, baseInput, commandCtx);

    const value = expectOk(result);
    expect(value.journalEntry).toEqual(existingEntry);
    expect(value.idempotent).toBe(true);
    expect(spies.insert).not.toHaveBeenCalled();
  });

  it("returns error when amount is zero or negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // no existing entry

    const result = await run(db, { ...baseInput, amount: 0 }, commandCtx);

    expectErr(result, InvalidAmountError);
  });

  it("returns error when amount is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // no existing entry

    const result = await run(db, { ...baseInput, amount: -100 }, commandCtx);

    expectErr(result, InvalidAmountError);
  });

  it("returns error when period is not OPEN or FUTURE_ENTERABLE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(neverOpenedPeriod); // period lookup

    const result = await run(
      db,
      { ...baseInput, accountingPeriodId: neverOpenedPeriod.id },
      commandCtx,
    );

    expectErr(result, InvalidPeriodStatusError);
  });

  it("returns error when period is CLOSED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(closedPeriod); // period lookup

    const result = await run(db, { ...baseInput, accountingPeriodId: closedPeriod.id }, commandCtx);

    expectErr(result, InvalidPeriodStatusError);
  });

  it("returns error when company does not match period company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(baseAccountingPeriod); // period lookup

    const result = await run(db, { ...baseInput, companyId: "other-company" }, commandCtx);

    expectErr(result, CompanyMismatchError);
  });

  it("returns error when debit account does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce(undefined); // debit account not found

    const result = await run(db, { ...baseInput, debitAccountId: "nonexistent" }, commandCtx);
    expectErr(result, AccountNotFoundError);
  });

  it("returns error when credit account does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce(baseAccount) // debit account lookup (active)
      .mockReturnValueOnce(undefined); // credit account not found

    const result = await run(db, { ...baseInput, creditAccountId: "nonexistent" }, commandCtx);
    expectErr(result, AccountNotFoundError);
  });

  it("returns error when debit account is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce(inactiveAccount); // debit account lookup

    const result = await run(db, { ...baseInput, debitAccountId: inactiveAccount.id }, commandCtx);

    expectErr(result, AccountNotActiveError);
  });

  it("returns error when credit account is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce(baseAccount) // debit account lookup (active)
      .mockReturnValueOnce(inactiveAccount); // credit account lookup

    const result = await run(db, { ...baseInput, creditAccountId: inactiveAccount.id }, commandCtx);

    expectErr(result, AccountNotActiveError);
  });

  it("creates journal entry with correct type and amounts", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdEntry = {
      ...baseJournalEntry,
      journalType: "INVENTORY",
      status: "POSTED",
      sourceDocumentReference: "INV-ADJ-001",
    };
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce(baseAccount) // debit account lookup
      .mockReturnValueOnce(baseAccount2); // credit account lookup
    spies.insert
      .mockReturnValueOnce(createdEntry) // journal entry insert
      .mockReturnValueOnce([]); // journal lines insert

    const result = await run(db, baseInput, commandCtx);

    const value = expectOk(result);
    expect(value.journalEntry.journalType).toBe("INVENTORY");
    expect(value.journalEntry.status).toBe("POSTED");
    expect(value.idempotent).toBe(false);
    expect(value.acknowledged).toBe(true);
  });

  it("handles multi-currency with exchange rate", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdEntry = {
      ...baseJournalEntry,
      journalType: "INVENTORY",
      status: "POSTED",
      sourceDocumentReference: "INV-ADJ-002",
    };
    spies.select
      .mockReturnValueOnce(undefined) // no existing entry
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce(baseAccount) // debit account lookup
      .mockReturnValueOnce(baseAccount2); // credit account lookup
    spies.insert
      .mockReturnValueOnce(createdEntry) // journal entry insert
      .mockReturnValueOnce([]); // journal lines insert

    const result = await run(
      db,
      {
        ...baseInput,
        sourceDocumentReference: "INV-ADJ-002",
        currencyCode: "currency-1",
        exchangeRate: 1.5,
        amount: 1000,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.journalEntry).toBeDefined();
    expect(value.idempotent).toBe(false);
    expect(spies.values).toHaveBeenCalled();
  });
});
