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 {
  CostSummaryNotFoundError,
  CostSummaryNotReviewableError,
  ParentOrderNotTechnicallyCompleteError,
  IncompleteVarianceBreakdownError,
  ReviewerRequiredError,
  VarianceCalculationFailedError,
} from "../lib/errors.generated";
import {
  basePendingReviewCostSummary,
  baseCollectingCostSummary,
  baseTechCompleteProductionOrder,
  baseInProgressProductionOrder,
} from "../testing/fixtures";
import { run } from "./reviewManufacturingCostSummary";
import type { VarianceBreakdownEntry } from "./reviewManufacturingCostSummary";

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

  const fullVarianceBreakdown: VarianceBreakdownEntry[] = [
    {
      varianceType: "MATERIAL_PRICE",
      amount: 100,
      accountReference: "acct-5001",
      variancePercentage: 5.0,
    },
    {
      varianceType: "MATERIAL_USAGE",
      amount: -20,
      accountReference: "acct-5002",
      variancePercentage: -1.0,
    },
    {
      varianceType: "LABOR_RATE",
      amount: 30,
      accountReference: "acct-5003",
      variancePercentage: 6.0,
    },
    {
      varianceType: "LABOR_EFFICIENCY",
      amount: -10,
      accountReference: "acct-5004",
      variancePercentage: -2.0,
    },
    {
      varianceType: "MACHINE_RATE",
      amount: 50,
      accountReference: "acct-5005",
      variancePercentage: 5.0,
    },
    {
      varianceType: "MACHINE_EFFICIENCY",
      amount: 0,
      accountReference: "acct-5006",
      variancePercentage: 0.0,
    },
    { varianceType: "SCRAP", amount: 50, accountReference: "acct-5007", variancePercentage: 100.0 },
    { varianceType: "YIELD", amount: 0, accountReference: "acct-5008", variancePercentage: 0.0 },
  ];

  const validInput = {
    costSummaryId: "cost-summary-2",
    reviewerId: "reviewer-1",
    reviewerNotes: "Variances within acceptable range",
    varianceBreakdown: fullVarianceBreakdown,
  };

  it("reviews a pending cost summary and freezes the variance breakdown", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([basePendingReviewCostSummary], [baseTechCompleteProductionOrder]);

    const updatedSummary = {
      ...basePendingReviewCostSummary,
      status: "VARIANCE_REVIEWED",
      reviewerNotes: "Variances within acceptable range",
    };
    mock.enqueueResults([], [updatedSummary]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.manufacturingCostSummary.status).toBe("VARIANCE_REVIEWED");
    }
    // 1 bulk insert containing 8 variance lines
    expect(mock.inserts).toHaveLength(1);
    const insertedRows = mock.inserts[0].insertRows();
    expect(insertedRows.length).toBe(8);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("returns error when the summary 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(CostSummaryNotFoundError);
    }
  });

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

    mock.enqueueResults([baseCollectingCostSummary]); // COLLECTING, not PENDING_VARIANCE_REVIEW

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

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

  it("returns error when the parent order is not technically complete", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([basePendingReviewCostSummary], [baseInProgressProductionOrder]); // not TECHNICALLY_COMPLETE

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

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

  it("returns error when the review result cannot represent all required variance types", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([basePendingReviewCostSummary], [baseTechCompleteProductionOrder]);

    // Missing YIELD from the breakdown
    const incompleteBreakdown = fullVarianceBreakdown.filter((v) => v.varianceType !== "YIELD");

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

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

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

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

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

  it("keeps all required variance types distinct during review", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([basePendingReviewCostSummary], [baseTechCompleteProductionOrder]);

    const updatedSummary = {
      ...basePendingReviewCostSummary,
      status: "VARIANCE_REVIEWED",
    };
    mock.enqueueResults([], [updatedSummary]);

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

    expect(result.ok).toBe(true);
    // Verify 1 bulk insert with 8 distinct variance lines
    expect(mock.inserts).toHaveLength(1);

    // Verify each row in the bulk insert had a distinct varianceType
    const insertedTypes = new Set<string>();
    for (const insert of mock.inserts) {
      for (const row of insert.insertRows()) {
        if (row.varianceType) {
          insertedTypes.add(row.varianceType as string);
        }
      }
    }
    expect(insertedTypes.size).toBe(8);
    expect(insertedTypes.has("MATERIAL_PRICE")).toBe(true);
    expect(insertedTypes.has("MATERIAL_USAGE")).toBe(true);
    expect(insertedTypes.has("LABOR_RATE")).toBe(true);
    expect(insertedTypes.has("LABOR_EFFICIENCY")).toBe(true);
    expect(insertedTypes.has("MACHINE_RATE")).toBe(true);
    expect(insertedTypes.has("MACHINE_EFFICIENCY")).toBe(true);
    expect(insertedTypes.has("SCRAP")).toBe(true);
    expect(insertedTypes.has("YIELD")).toBe(true);
  });

  it("returns error when final variance cannot be recalculated consistently", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([basePendingReviewCostSummary], [baseTechCompleteProductionOrder]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          ...validInput,
          varianceBreakdown: [
            { ...fullVarianceBreakdown[0], amount: Number.NaN },
            ...fullVarianceBreakdown.slice(1),
          ],
        },
        ctx,
      ),
    );

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