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,
  WorkCenterNotActivatableError,
  MissingCalendarContextError,
  InvalidCapacityError,
  InvalidRateError,
  OverheadCurrencyRequiredError,
} from "../lib/errors.generated";
import {
  baseDraftWorkCenter,
  baseActiveWorkCenter,
  baseInactiveWorkCenter,
} from "../testing/fixtures";
import { run } from "./activateWorkCenter";

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

  it("activates a valid draft work center", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activated = { ...baseDraftWorkCenter, status: "ACTIVE" as const };

    mock.enqueueResults([baseDraftWorkCenter], [activated]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.status).toBe("ACTIVE");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("reactivates a valid inactive work center", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reactivated = { ...baseInactiveWorkCenter, status: "ACTIVE" as const };

    mock.enqueueResults([baseInactiveWorkCenter], [reactivated]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.status).toBe("ACTIVE");
    }
    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, { id: "nonexistent" }, ctx));

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

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

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

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

  it("returns error when required calendar context is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const noCalendar = { ...baseDraftWorkCenter, calendarReference: null };
    mock.enqueueResults([noCalendar]);

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

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

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

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

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

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

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

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

  it("returns error when fixed overhead is missing its currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([
      {
        ...baseDraftWorkCenter,
        overheadAbsorptionMethod: "FIXED_AMOUNT_PER_GOOD_UNIT",
        overheadAbsorptionCurrency: null,
      },
    ]);

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

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