import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  WorkCenterNotFoundError,
  InvalidCapacityError,
  InvalidRateError,
  OverheadCurrencyRequiredError,
} from "../lib/errors.generated";
import { baseActiveWorkCenter } from "../testing/fixtures";
import { run } from "./updateWorkCenter";

describe("updateWorkCenter", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing:manufacturing:updateWorkCenter"],
  };

  const validInput = {
    id: baseActiveWorkCenter.id,
    capacityAssumptions: 200,
    laborRate: 30.0,
  };

  it("updates an active work center without changing scope identity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseActiveWorkCenter],
      [{ ...baseActiveWorkCenter, capacityAssumptions: 200, laborRate: 30.0 }],
    );

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.capacityAssumptions).toBe(200);
      expect(result.value.workCenter.laborRate).toBe(30.0);
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(WorkCenterNotFoundError);
    }
  });

  it("looks up a work center by companyId, siteId, and code", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseActiveWorkCenter],
      [{ ...baseActiveWorkCenter, capacityAssumptions: 220 }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          companyId: baseActiveWorkCenter.companyId,
          siteId: baseActiveWorkCenter.siteId,
          code: baseActiveWorkCenter.code,
          capacityAssumptions: 220,
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.capacityAssumptions).toBe(220);
    }
  });

  it("returns error when capacity is not positive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveWorkCenter]);

    const result = await mock.withTx((trx) =>
      run(trx, { ...validInput, capacityAssumptions: 0 }, ctx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidCapacityError);
    }
  });

  it("returns error when a rate is negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveWorkCenter]);

    const result = await mock.withTx((trx) => run(trx, { ...validInput, laborRate: -1 }, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidRateError);
    }
  });

  it("preserves released cost baselines after update", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveWorkCenter], [{ ...baseActiveWorkCenter, machineRate: 75.0 }]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: baseActiveWorkCenter.id, machineRate: 75.0 }, ctx),
    );

    expect(result.ok).toBe(true);
    expect(mock.updates).toHaveLength(1);
    expect(mock.updates[0].updateValues()).toEqual(expect.objectContaining({ machineRate: 75.0 }));
    expect(mock.updates[0].updateValues()).toEqual(
      // oxlint-disable-next-line typescript/no-unsafe-assignment -- vitest matcher type
      expect.not.objectContaining({ companyId: expect.anything() }),
    );
  });

  it("returns error when fixed-amount overhead omits currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveWorkCenter]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseActiveWorkCenter.id,
          overheadAbsorptionMethod: "FIXED_AMOUNT_PER_GOOD_UNIT",
          overheadAbsorptionCurrency: null,
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(OverheadCurrencyRequiredError);
    }
  });
});
