import { describe, expect, it } from "vitest";
import {
  computeCommercialTermsSummary,
  computeMilestoneAmounts,
  defaultCommercialTerms,
  validatePaymentMilestones,
} from "../estimate/commercial-terms.js";
import type { CommercialTerms, PaymentMilestone } from "@capakraken/shared";

const BASE_TERMS: CommercialTerms = {
  pricingModel: "fixed_price",
  contingencyPercent: 0,
  discountPercent: 0,
  paymentTermDays: 30,
  paymentMilestones: [],
  warrantyMonths: 0,
};

describe("computeCommercialTermsSummary", () => {
  it("returns unchanged totals when contingency and discount are 0", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 100_000_00,
      basePriceCents: 150_000_00,
      terms: BASE_TERMS,
    });

    expect(result.adjustedCostCents).toBe(100_000_00);
    expect(result.adjustedPriceCents).toBe(150_000_00);
    expect(result.contingencyCents).toBe(0);
    expect(result.discountCents).toBe(0);
    expect(result.adjustedMarginCents).toBe(50_000_00);
  });

  it("adds contingency to cost", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 100_000_00,
      basePriceCents: 150_000_00,
      terms: { ...BASE_TERMS, contingencyPercent: 10 },
    });

    expect(result.contingencyCents).toBe(10_000_00);
    expect(result.adjustedCostCents).toBe(110_000_00);
    expect(result.adjustedPriceCents).toBe(150_000_00);
    expect(result.adjustedMarginCents).toBe(40_000_00);
  });

  it("subtracts discount from price", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 100_000_00,
      basePriceCents: 200_000_00,
      terms: { ...BASE_TERMS, discountPercent: 5 },
    });

    expect(result.discountCents).toBe(10_000_00);
    expect(result.adjustedPriceCents).toBe(190_000_00);
    expect(result.adjustedCostCents).toBe(100_000_00);
    expect(result.adjustedMarginCents).toBe(90_000_00);
  });

  it("applies both contingency and discount together", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 100_000_00,
      basePriceCents: 200_000_00,
      terms: { ...BASE_TERMS, contingencyPercent: 15, discountPercent: 10 },
    });

    // cost: 100k + 15% = 115k
    expect(result.adjustedCostCents).toBe(115_000_00);
    // price: 200k - 10% = 180k
    expect(result.adjustedPriceCents).toBe(180_000_00);
    // margin: 180k - 115k = 65k
    expect(result.adjustedMarginCents).toBe(65_000_00);
  });

  it("computes margin percent correctly", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 70_000_00,
      basePriceCents: 100_000_00,
      terms: BASE_TERMS,
    });

    expect(result.adjustedMarginPercent).toBeCloseTo(30, 1);
  });

  it("handles zero price gracefully (margin% = 0)", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 50_000_00,
      basePriceCents: 0,
      terms: BASE_TERMS,
    });

    expect(result.adjustedMarginPercent).toBe(0);
    expect(result.adjustedMarginCents).toBe(-50_000_00);
  });

  it("handles negative margin when discount exceeds buffer", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 100_000_00,
      basePriceCents: 110_000_00,
      terms: { ...BASE_TERMS, contingencyPercent: 20, discountPercent: 10 },
    });

    // cost: 100k + 20% = 120k, price: 110k - 10% = 99k → margin = -21k
    expect(result.adjustedMarginCents).toBe(-21_000_00);
    expect(result.adjustedMarginPercent).toBeLessThan(0);
  });

  it("rounds contingency and discount to integer cents", () => {
    const result = computeCommercialTermsSummary({
      baseCostCents: 33_333,
      basePriceCents: 66_667,
      terms: { ...BASE_TERMS, contingencyPercent: 7.5, discountPercent: 3.3 },
    });

    expect(Number.isInteger(result.contingencyCents)).toBe(true);
    expect(Number.isInteger(result.discountCents)).toBe(true);
    expect(Number.isInteger(result.adjustedCostCents)).toBe(true);
    expect(Number.isInteger(result.adjustedPriceCents)).toBe(true);
  });
});

describe("validatePaymentMilestones", () => {
  it("returns no warnings for empty milestones", () => {
    expect(validatePaymentMilestones([])).toEqual([]);
  });

  it("returns no warnings when milestones sum to 100%", () => {
    const milestones: PaymentMilestone[] = [
      { label: "Kickoff", percent: 30 },
      { label: "Midpoint", percent: 40 },
      { label: "Delivery", percent: 30 },
    ];
    expect(validatePaymentMilestones(milestones)).toEqual([]);
  });

  it("warns when milestones do not sum to 100%", () => {
    const milestones: PaymentMilestone[] = [
      { label: "Kickoff", percent: 30 },
      { label: "Delivery", percent: 50 },
    ];
    const warnings = validatePaymentMilestones(milestones);
    expect(warnings).toHaveLength(1);
    expect(warnings[0]).toContain("80.0%");
  });

  it("warns about zero-percent milestones", () => {
    const milestones: PaymentMilestone[] = [
      { label: "Kickoff", percent: 0 },
      { label: "Delivery", percent: 100 },
    ];
    const warnings = validatePaymentMilestones(milestones);
    expect(warnings.some((w) => w.includes("0%"))).toBe(true);
  });

  it("warns about empty labels", () => {
    const milestones: PaymentMilestone[] = [
      { label: "  ", percent: 50 },
      { label: "End", percent: 50 },
    ];
    const warnings = validatePaymentMilestones(milestones);
    expect(warnings.some((w) => w.includes("empty label"))).toBe(true);
  });

  it("warns about non-chronological dates", () => {
    const milestones: PaymentMilestone[] = [
      { label: "Late", percent: 50, dueDate: "2026-06-01" },
      { label: "Early", percent: 50, dueDate: "2026-03-01" },
    ];
    const warnings = validatePaymentMilestones(milestones);
    expect(warnings.some((w) => w.includes("earlier date"))).toBe(true);
  });

  it("ignores date order for milestones without dates", () => {
    const milestones: PaymentMilestone[] = [
      { label: "A", percent: 50 },
      { label: "B", percent: 50, dueDate: "2026-01-01" },
    ];
    expect(validatePaymentMilestones(milestones)).toEqual([]);
  });
});

describe("computeMilestoneAmounts", () => {
  it("computes amounts from adjusted price", () => {
    const milestones: PaymentMilestone[] = [
      { label: "Kickoff", percent: 30 },
      { label: "Final", percent: 70 },
    ];
    const amounts = computeMilestoneAmounts(100_000_00, milestones);

    expect(amounts).toHaveLength(2);
    expect(amounts[0]!.amountCents).toBe(30_000_00);
    expect(amounts[1]!.amountCents).toBe(70_000_00);
  });

  it("rounds amounts to integer cents", () => {
    const milestones: PaymentMilestone[] = [
      { label: "A", percent: 33.33 },
      { label: "B", percent: 33.33 },
      { label: "C", percent: 33.34 },
    ];
    const amounts = computeMilestoneAmounts(99_999, milestones);
    for (const a of amounts) {
      expect(Number.isInteger(a.amountCents)).toBe(true);
    }
  });

  it("preserves due dates", () => {
    const milestones: PaymentMilestone[] = [
      { label: "M1", percent: 100, dueDate: "2026-06-15" },
    ];
    const amounts = computeMilestoneAmounts(50_000_00, milestones);
    expect(amounts[0]!.dueDate).toBe("2026-06-15");
  });
});

describe("defaultCommercialTerms", () => {
  it("returns valid defaults", () => {
    const terms = defaultCommercialTerms();
    expect(terms.pricingModel).toBe("fixed_price");
    expect(terms.contingencyPercent).toBe(0);
    expect(terms.discountPercent).toBe(0);
    expect(terms.paymentTermDays).toBe(30);
    expect(terms.paymentMilestones).toEqual([]);
    expect(terms.warrantyMonths).toBe(0);
  });
});
