import { describe, it, expect } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  JournalEntryNotFoundError,
  InvalidStatusForLineAddError,
  AccountNotFoundError,
  AccountNotActiveError,
  InvalidDebitCreditError,
  CurrencyNotFoundError,
} from "../lib/errors.generated";
import {
  baseJournalEntry,
  postedJournalEntry,
  reversedJournalEntry,
  baseAccount,
  baseAccount2,
  inactiveAccount,
  baseCurrency,
  baseJournalLine,
} from "../testing/fixtures";
import { run } from "./addJournalLine";

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

    const result = await run(
      db,
      {
        journalEntryId: "missing-entry",
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, JournalEntryNotFoundError);
  });

  it("returns error when journal entry is in POSTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(postedJournalEntry);

    const result = await run(
      db,
      {
        journalEntryId: postedJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, InvalidStatusForLineAddError);
  });

  it("returns error when journal entry is in REVERSED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(reversedJournalEntry);

    const result = await run(
      db,
      {
        journalEntryId: reversedJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, InvalidStatusForLineAddError);
  });

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

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: "missing-account",
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, AccountNotFoundError);
  });

  it("returns error when GL account is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(inactiveAccount);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: inactiveAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, AccountNotActiveError);
  });

  it("returns error when both debit and credit amounts are specified", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: 500,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, InvalidDebitCreditError);
  });

  it("returns error when both debit and credit amounts are zero", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: null,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, InvalidDebitCreditError);
  });

  it("returns error when debit amount is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: -100,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, InvalidDebitCreditError);
  });

  it("returns error when credit amount is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: null,
        creditAmount: -200,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectErr(result, InvalidDebitCreditError);
  });

  it("returns error when currency does not exist for multi-currency line", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseJournalEntry)
      .mockReturnValueOnce(baseAccount)
      .mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: "missing-currency",
        exchangeRate: 1.5,
      },
      commandCtx,
    );

    expectErr(result, CurrencyNotFoundError);
  });

  it("adds journal line with debit amount to DRAFT entry", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);
    spies.insert.mockReturnValueOnce(baseJournalLine);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: "Debit line",
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.journalLine).toEqual(baseJournalLine);
  });

  it("adds journal line with credit amount to DRAFT entry", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const creditLine = {
      ...baseJournalLine,
      id: "journal-line-credit",
      debitAmount: null,
      creditAmount: 500,
      functionalDebitAmount: null,
      functionalCreditAmount: 500,
    };
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount2);
    spies.insert.mockReturnValueOnce(creditLine);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount2.id,
        debitAmount: null,
        creditAmount: 500,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.journalLine).toEqual(creditLine);
  });

  it("adds multi-currency journal line with currency and exchange rate", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const multiCurrencyLine = {
      ...baseJournalLine,
      id: "journal-line-multi",
      debitAmount: 1000,
      currencyCode: baseCurrency.code,
      exchangeRate: 1.5,
      functionalDebitAmount: 1500,
      functionalCreditAmount: null,
    };
    spies.select
      .mockReturnValueOnce(baseJournalEntry)
      .mockReturnValueOnce(baseAccount)
      .mockReturnValueOnce(baseCurrency);
    spies.insert.mockReturnValueOnce(multiCurrencyLine);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: baseCurrency.code,
        exchangeRate: 1.5,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.journalLine).toEqual(multiCurrencyLine);
  });

  it("defaults to functional currency with exchange rate 1.0 when currency not specified", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);
    spies.insert.mockReturnValueOnce(baseJournalLine);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.journalLine).toBeDefined();
    expect(spies.insert).toHaveBeenCalled();
  });

  it("computes functional currency amount as foreign amount multiplied by exchange rate", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const computedLine = {
      ...baseJournalLine,
      id: "journal-line-computed",
      debitAmount: null,
      creditAmount: 200,
      currencyCode: baseCurrency.code,
      exchangeRate: 2.5,
      functionalDebitAmount: null,
      functionalCreditAmount: 500,
    };
    spies.select
      .mockReturnValueOnce(baseJournalEntry)
      .mockReturnValueOnce(baseAccount)
      .mockReturnValueOnce(baseCurrency);
    spies.insert.mockReturnValueOnce(computedLine);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: null,
        creditAmount: 200,
        description: null,
        currencyCode: baseCurrency.code,
        exchangeRate: 2.5,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.journalLine).toEqual(computedLine);
    expect(spies.insert).toHaveBeenCalled();
  });

  it("adds journal line with optional description", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const lineWithDesc = {
      ...baseJournalLine,
      description: "Office supplies purchase",
    };
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);
    spies.insert.mockReturnValueOnce(lineWithDesc);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: "Office supplies purchase",
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.journalLine.description).toBe("Office supplies purchase");
  });

  it("emits audit event recording line addition and acting user", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseJournalEntry).mockReturnValueOnce(baseAccount);
    spies.insert.mockReturnValueOnce(baseJournalLine);

    const result = await run(
      db,
      {
        journalEntryId: baseJournalEntry.id,
        accountId: baseAccount.id,
        debitAmount: 1000,
        creditAmount: null,
        description: null,
        currencyCode: null,
        exchangeRate: null,
      },
      commandCtx,
    );

    expectOk(result);
    expect(spies.insert).toHaveBeenCalled();
  });
});
