import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChannelNotFoundError,
  CrossCompanyReferenceError,
  ExternalOrderIdRequiredError,
} from "../lib/errors.generated";
import { baseChannel, baseChannelOrder, baseCompany } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./recordChannelOrder";

describe("recordChannelOrder", () => {
  it("creates a new pending channel order from inbound payload", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannel).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValueOnce(baseChannelOrder);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        channelId: baseChannel.id,
        externalOrderId: baseChannelOrder.externalOrderId,
        customerId: baseChannelOrder.customerId,
        currencyId: baseChannelOrder.currencyId,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.channelOrder.status).toBe("PENDING_CONVERSION");
  });

  it("updates an existing channel order idempotently on duplicate delivery", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseChannelOrder, updatedAt: new Date("2024-01-02T00:00:00.000Z") };
    spies.select.mockReturnValueOnce(baseChannel).mockReturnValueOnce(baseChannelOrder);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        channelId: baseChannel.id,
        externalOrderId: baseChannelOrder.externalOrderId,
        rawPayload: { orderId: "EXT-001", replay: true },
      },
      commandCtx,
    );

    expectOk(result);
  });

  it("preserves raw troubleshooting context", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannel).mockReturnValueOnce(baseChannelOrder);
    spies.update.mockReturnValueOnce(baseChannelOrder);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        channelId: baseChannel.id,
        externalOrderId: baseChannelOrder.externalOrderId,
        rawPayload: { orderId: "EXT-001", source: "webhook" },
      },
      commandCtx,
    );

    expectOk(result);
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({
        rawPayload: JSON.stringify({ orderId: "EXT-001", source: "webhook" }),
      }),
    );
  });

  it("throws when external order identity is missing", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(
      db,
      { companyId: baseCompany.id, channelId: baseChannel.id, externalOrderId: "" },
      commandCtx,
    );

    expectErr(result, ExternalOrderIdRequiredError);
  });

  it("throws when the channel does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        channelId: baseChannel.id,
        externalOrderId: baseChannelOrder.externalOrderId,
      },
      commandCtx,
    );

    expectErr(result, ChannelNotFoundError);
  });

  it("throws on cross-company reference", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseChannel, companyId: "company-2" });

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        channelId: baseChannel.id,
        externalOrderId: baseChannelOrder.externalOrderId,
      },
      commandCtx,
    );

    expectErr(result, CrossCompanyReferenceError);
  });
});
