import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("activates a valid draft work center", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activated = { ...baseDraftWorkCenter, status: "ACTIVE" as const };

    spies.select.mockReturnValueOnce(baseDraftWorkCenter);
    spies.update.mockReturnValue(activated);

    const result = await run(db, { id: baseDraftWorkCenter.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.status).toBe("ACTIVE");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("reactivates a valid inactive work center", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reactivated = { ...baseInactiveWorkCenter, status: "ACTIVE" as const };

    spies.select.mockReturnValueOnce(baseInactiveWorkCenter);
    spies.update.mockReturnValue(reactivated);

    const result = await run(db, { id: baseInactiveWorkCenter.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.status).toBe("ACTIVE");
    }
    expect(spies.update).toHaveBeenCalled();
  });

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

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    const noCalendar = { ...baseDraftWorkCenter, calendarReference: null };
    spies.select.mockReturnValueOnce(noCalendar);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    const zeroCapacity = { ...baseDraftWorkCenter, capacityAssumptions: 0 };
    spies.select.mockReturnValueOnce(zeroCapacity);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseDraftWorkCenter, laborRate: -1 });

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({
      ...baseDraftWorkCenter,
      overheadAbsorptionMethod: "FIXED_AMOUNT_PER_GOOD_UNIT",
      overheadAbsorptionCurrency: null,
    });

    const result = await run(db, { id: baseDraftWorkCenter.id }, ctx);

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