import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidLegalNameError,
  CurrencyNotFoundError,
  CurrencyImmutableError,
} from "../lib/errors.generated";
import { draftCompany, activeCompany, inactiveCompany } from "../testing/fixtures";
import { getCurrency } from "../../primitives/query/getCurrency.generated";
import { run } from "./updateCompany";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

const ctx: CommandContext = {
  actorId: "test-actor",
  permissions: ["organization:updateCompany"],
};

const deps = { getCurrency };

describe("updateCompany", () => {
  it("updates legal name on DRAFT company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCompany = { ...draftCompany, legalName: "New Name" };
    spies.select.mockReturnValueOnce(draftCompany);
    spies.update.mockReturnValue(updatedCompany);

    const result = await run(
      db,
      {
        companyId: draftCompany.id,
        legalName: "New Name",
      },
      ctx,
      deps,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.company.legalName).toBe("New Name");
    }
  });

  it("updates address fields on ACTIVE company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCompany = { ...activeCompany, street: "789 New Ave" };
    spies.select.mockReturnValueOnce(activeCompany);
    spies.update.mockReturnValue(updatedCompany);

    const result = await run(
      db,
      {
        companyId: activeCompany.id,
        street: "789 New Ave",
        city: "Kyoto",
      },
      ctx,
      deps,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.company.street).toBe("789 New Ave");
    }
  });

  it("updates tax ID and registration number", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCompany = { ...draftCompany, taxId: "NEW-TAX", registrationNumber: "NEW-REG" };
    spies.select.mockReturnValueOnce(draftCompany);
    spies.update.mockReturnValue(updatedCompany);

    const result = await run(
      db,
      {
        companyId: draftCompany.id,
        taxId: "NEW-TAX",
        registrationNumber: "NEW-REG",
      },
      ctx,
      deps,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.company.taxId).toBe("NEW-TAX");
      expect(result.value.company.registrationNumber).toBe("NEW-REG");
    }
  });

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

    const result = await run(
      db,
      {
        companyId: "nonexistent",
        legalName: "New Name",
      },
      ctx,
      deps,
    );

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

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

    const result = await run(
      db,
      {
        companyId: draftCompany.id,
        legalName: "",
      },
      ctx,
      deps,
    );

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

  it("returns error when changing base currency on ACTIVE company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeCompany);

    const result = await run(
      db,
      {
        companyId: activeCompany.id,
        baseCurrencyId: "new-currency",
      },
      ctx,
      deps,
    );

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

  it("returns error when changing base currency on INACTIVE company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveCompany);

    const result = await run(
      db,
      {
        companyId: inactiveCompany.id,
        baseCurrencyId: "new-currency",
      },
      ctx,
      deps,
    );

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

  it("returns error when new base currency does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(draftCompany) // company lookup
      .mockReturnValueOnce(undefined); // getCurrency returns null

    const result = await run(
      db,
      {
        companyId: draftCompany.id,
        baseCurrencyId: "nonexistent-currency",
      },
      ctx,
      deps,
    );

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

  it("returns error when new base currency is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(draftCompany) // company lookup
      .mockReturnValueOnce({ id: "currency-inactive", isActive: false }); // getCurrency returns inactive

    const result = await run(
      db,
      {
        companyId: draftCompany.id,
        baseCurrencyId: "currency-inactive",
      },
      ctx,
      deps,
    );

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

  it("updates base currency on DRAFT company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCompany = { ...draftCompany, baseCurrencyId: "currency-eur" };
    spies.select
      .mockReturnValueOnce(draftCompany) // company lookup
      .mockReturnValueOnce({ id: "currency-eur", isActive: true }); // getCurrency
    spies.update.mockReturnValue(updatedCompany);

    const result = await run(
      db,
      {
        companyId: draftCompany.id,
        baseCurrencyId: "currency-eur",
      },
      ctx,
      deps,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.company.baseCurrencyId).toBe("currency-eur");
    }
  });
});
