import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  ChannelNotFoundError,
  CrossCompanyReferenceError,
  ExternalOrderIdRequiredError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { baseChannel, baseChannelOrder, baseCompany } from "../testing/fixtures";
import { run } from "./recordChannelOrder";

describe("recordChannelOrder", () => {
  it("creates a new pending channel order from inbound payload", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel], [], [baseChannelOrder]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseChannelOrder, updatedAt: new Date("2024-01-02T00:00:00.000Z") };
    mock.enqueueResults([baseChannel], [baseChannelOrder], [updated]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel], [baseChannelOrder], [baseChannelOrder]);

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

    expectOk(result);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({
        rawPayload: JSON.stringify({ orderId: "EXT-001", source: "webhook" }),
      }),
    );
  });

  it("throws when external order identity is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

    expectErr(result, ExternalOrderIdRequiredError);
  });

  it("throws when the channel does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

    expectErr(result, ChannelNotFoundError);
  });

  it("throws on cross-company reference", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseChannel, companyId: "company-2" }]);

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

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