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 {
  InvalidScopeError,
  DuplicateWorkCenterCodeError,
  InvalidCapacityError,
  InvalidRateError,
  OverheadCurrencyRequiredError,
} from "../lib/errors.generated";
import { baseDraftWorkCenter } from "../testing/fixtures";
import { run } from "./createWorkCenter";

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

  const validInput = {
    code: "WC-NEW",
    companyId: "company-1",
    siteId: "site-1",
    capacityAssumptions: 100,
    laborRate: 25.0,
    machineRate: 50.0,
    calendarReference: "cal-standard",
  };

  it("creates a draft work center with positive capacity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdWorkCenter = {
      ...baseDraftWorkCenter,
      id: "new-wc-id",
      code: "WC-NEW",
    };

    mock.enqueueResults([], [createdWorkCenter]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.status).toBe("DRAFT");
      expect(result.value.workCenter.code).toBe("WC-NEW");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("returns error when scope is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

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

  it("creates a draft work center without siteId when not required", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdWorkCenter = {
      ...baseDraftWorkCenter,
      id: "new-wc-id",
      code: "WC-NEW",
      siteId: null,
    };

    mock.enqueueResults([], [createdWorkCenter]);

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

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

  it("returns error when the code already exists in scope", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftWorkCenter]);

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

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

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

    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"]>();

    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("returns error when fixed-amount overhead omits currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

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