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

describe("reviewManufacturingCostSummary", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["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 { db, spies } = createMockDb<Transaction>();

    // select: cost summary, production order
    spies.select.mockReturnValueOnce(basePendingReviewCostSummary);
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);

    const updatedSummary = {
      ...basePendingReviewCostSummary,
      status: "VARIANCE_REVIEWED",
      reviewerNotes: "Variances within acceptable range",
    };
    spies.insert.mockReturnValue({});
    spies.update.mockReturnValue(updatedSummary);

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.manufacturingCostSummary.status).toBe("VARIANCE_REVIEWED");
    }
    // 8 variance lines inserted
    expect(spies.insert).toHaveBeenCalledTimes(8);
    expect(spies.update).toHaveBeenCalled();
  });

  it("returns error when the summary does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(undefined);

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

    spies.select.mockReturnValueOnce(baseCollectingCostSummary); // COLLECTING, not PENDING_VARIANCE_REVIEW

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

    spies.select.mockReturnValueOnce(basePendingReviewCostSummary);
    spies.select.mockReturnValueOnce(baseInProgressProductionOrder); // not TECHNICALLY_COMPLETE

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

    spies.select.mockReturnValueOnce(basePendingReviewCostSummary);
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);

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

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

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

    spies.select.mockReturnValueOnce(basePendingReviewCostSummary);
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);

    const updatedSummary = {
      ...basePendingReviewCostSummary,
      status: "VARIANCE_REVIEWED",
    };
    spies.insert.mockReturnValue({});
    spies.update.mockReturnValue(updatedSummary);

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(true);
    // Verify all 8 distinct variance lines were inserted
    expect(spies.insert).toHaveBeenCalledTimes(8);

    // Verify each call used the correct variance type through the values spy
    const insertedTypes = new Set<string>();
    for (const call of spies.values.mock.calls) {
      const values = call[0] as Record<string, unknown>;
      if (values.varianceType) {
        insertedTypes.add(values.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 { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(basePendingReviewCostSummary);
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);

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

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