import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidAllocationTypeError,
  AccountingPeriodNotFoundError,
  InvalidNameError,
} from "../lib/errors.generated";
import { baseCompany, baseAccountingPeriod, baseAllocationCycle } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createAllocationCycle";

describe("createAllocationCycle", () => {
  it("creates allocation cycle in DRAFT status with required fields", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany).mockReturnValueOnce(baseAccountingPeriod);
    spies.insert.mockReturnValueOnce(baseAllocationCycle);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        name: "Q1 2024 Overhead",
        allocationType: "ASSESSMENT",
        accountingPeriodId: baseAccountingPeriod.id,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.allocationCycle).toEqual(baseAllocationCycle);
  });

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

    const result = await run(
      db,
      {
        companyId: "missing-company",
        name: "Q1 2024 Overhead",
        allocationType: "ASSESSMENT",
        accountingPeriodId: baseAccountingPeriod.id,
      },
      commandCtx,
    );

    expectErr(result, CompanyNotFoundError);
  });

  it("returns error when company is not ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseCompany, status: "INACTIVE" });

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        name: "Q1 2024 Overhead",
        allocationType: "ASSESSMENT",
        accountingPeriodId: baseAccountingPeriod.id,
      },
      commandCtx,
    );

    expectErr(result, CompanyNotFoundError);
  });

  it("returns error when allocation type is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        name: "Q1 2024 Overhead",
        allocationType: "INVALID_TYPE",
        accountingPeriodId: baseAccountingPeriod.id,
      },
      commandCtx,
    );

    expectErr(result, InvalidAllocationTypeError);
  });

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

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        name: "Q1 2024 Overhead",
        allocationType: "ASSESSMENT",
        accountingPeriodId: "missing-period",
      },
      commandCtx,
    );

    expectErr(result, AccountingPeriodNotFoundError);
  });

  it("returns error when name is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany).mockReturnValueOnce(baseAccountingPeriod);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        name: "",
        allocationType: "ASSESSMENT",
        accountingPeriodId: baseAccountingPeriod.id,
      },
      commandCtx,
    );

    expectErr(result, InvalidNameError);
  });

  it("allocation cycles from different companies are isolated", async () => {
    const companyB = { id: "company-2", status: "ACTIVE" };
    const cycleB = { ...baseAllocationCycle, id: "cycle-b", companyId: companyB.id };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyB).mockReturnValueOnce(baseAccountingPeriod);
    spies.insert.mockReturnValueOnce(cycleB);

    const result = await run(
      db,
      {
        companyId: companyB.id,
        name: "Q1 2024 Overhead",
        allocationType: "ASSESSMENT",
        accountingPeriodId: baseAccountingPeriod.id,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.allocationCycle.companyId).toBe(companyB.id);
  });

  it("emits audit event recording acting user, timestamp, and initial field values", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany).mockReturnValueOnce(baseAccountingPeriod);
    spies.insert.mockReturnValueOnce(baseAllocationCycle);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        name: "Q1 2024 Overhead",
        allocationType: "ASSESSMENT",
        accountingPeriodId: baseAccountingPeriod.id,
      },
      commandCtx,
    );

    expectOk(result);
    expect(spies.insert).toHaveBeenCalled();
  });
});
