import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AllocationCycleNotFoundError,
  InvalidStateError,
  SenderNotFoundError,
  ReceiverNotFoundError,
  SenderIsReceiverError,
  InvalidPercentageError,
} from "../lib/errors.generated";
import {
  baseAllocationCycle,
  validatedAllocationCycle,
  baseCostCenter,
  baseCostCenter2,
  baseAllocationRule,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createAllocationRule";

describe("createAllocationRule", () => {
  it("adds an allocation rule to a DRAFT allocation cycle", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAllocationCycle) // cycle lookup
      .mockReturnValueOnce(baseCostCenter) // sender lookup
      .mockReturnValueOnce(baseCostCenter2); // receiver lookup
    spies.insert.mockReturnValueOnce(baseAllocationRule);

    const result = await run(
      db,
      {
        allocationCycleId: baseAllocationCycle.id,
        senderCostCenterId: baseCostCenter.id,
        receiverType: "CostCenter",
        receiverId: baseCostCenter2.id,
        percentage: 100,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.allocationRule).toEqual(baseAllocationRule);
  });

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

    const result = await run(
      db,
      {
        allocationCycleId: "missing-id",
        senderCostCenterId: baseCostCenter.id,
        receiverType: "CostCenter",
        receiverId: baseCostCenter2.id,
        percentage: 100,
      },
      commandCtx,
    );

    expectErr(result, AllocationCycleNotFoundError);
  });

  it("returns error when allocation cycle is not in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(validatedAllocationCycle);

    const result = await run(
      db,
      {
        allocationCycleId: validatedAllocationCycle.id,
        senderCostCenterId: baseCostCenter.id,
        receiverType: "CostCenter",
        receiverId: baseCostCenter2.id,
        percentage: 100,
      },
      commandCtx,
    );

    expectErr(result, InvalidStateError);
  });

  it("returns error when sender cost center does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAllocationCycle) // cycle
      .mockReturnValueOnce(undefined); // sender

    const result = await run(
      db,
      {
        allocationCycleId: baseAllocationCycle.id,
        senderCostCenterId: "missing-sender",
        receiverType: "CostCenter",
        receiverId: baseCostCenter2.id,
        percentage: 100,
      },
      commandCtx,
    );

    expectErr(result, SenderNotFoundError);
  });

  it("returns error when a receiver cost object does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAllocationCycle) // cycle
      .mockReturnValueOnce(baseCostCenter) // sender
      .mockReturnValueOnce(undefined); // receiver

    const result = await run(
      db,
      {
        allocationCycleId: baseAllocationCycle.id,
        senderCostCenterId: baseCostCenter.id,
        receiverType: "CostCenter",
        receiverId: "missing-receiver",
        percentage: 100,
      },
      commandCtx,
    );

    expectErr(result, ReceiverNotFoundError);
  });

  it("returns error when sender appears as a receiver", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAllocationCycle) // cycle
      .mockReturnValueOnce(baseCostCenter) // sender
      .mockReturnValueOnce(baseCostCenter); // receiver (same as sender)

    const result = await run(
      db,
      {
        allocationCycleId: baseAllocationCycle.id,
        senderCostCenterId: baseCostCenter.id,
        receiverType: "CostCenter",
        receiverId: baseCostCenter.id,
        percentage: 100,
      },
      commandCtx,
    );

    expectErr(result, SenderIsReceiverError);
  });

  it("returns error when percentage value is zero or negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAllocationCycle) // cycle
      .mockReturnValueOnce(baseCostCenter) // sender
      .mockReturnValueOnce(baseCostCenter2); // receiver

    const result = await run(
      db,
      {
        allocationCycleId: baseAllocationCycle.id,
        senderCostCenterId: baseCostCenter.id,
        receiverType: "CostCenter",
        receiverId: baseCostCenter2.id,
        percentage: 0,
      },
      commandCtx,
    );

    expectErr(result, InvalidPercentageError);
  });

  it("emits audit event recording the rule creation and acting user", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseAllocationCycle)
      .mockReturnValueOnce(baseCostCenter)
      .mockReturnValueOnce(baseCostCenter2);
    spies.insert.mockReturnValueOnce(baseAllocationRule);

    const result = await run(
      db,
      {
        allocationCycleId: baseAllocationCycle.id,
        senderCostCenterId: baseCostCenter.id,
        receiverType: "CostCenter",
        receiverId: baseCostCenter2.id,
        percentage: 100,
      },
      commandCtx,
    );

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