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

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

const deps = { getCurrency };

describe("activateCompany", () => {
  it("activates DRAFT company with all required fields", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activatedCompany = { ...draftCompany, status: "ACTIVE" };
    spies.select
      .mockReturnValueOnce(draftCompany) // company lookup
      .mockReturnValueOnce({ id: "currency-usd", isActive: true }); // getCurrency
    spies.update.mockReturnValue(activatedCompany);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.company.status).toBe("ACTIVE");
    }
  });

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

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

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

  it("throws when company is already ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeCompany);

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

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

  it("throws when company is INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveCompany);

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

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

  it("throws when legal name is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const companyNoLegalName = { ...draftCompany, legalName: "" };
    spies.select.mockReturnValueOnce(companyNoLegalName);

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

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

  it("throws when base currency is not assigned", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftCompanyNoCurrency);

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

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

  it("throws when base currency references a non-existent Currency", 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 }, ctx, deps);

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

  it("throws when base currency references an inactive Currency", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(draftCompany) // company lookup
      .mockReturnValueOnce({ id: "currency-usd", isActive: false }); // getCurrency inactive

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

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

  it("throws when address street is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const companyNoStreet = { ...draftCompany, street: null };
    spies.select.mockReturnValueOnce(companyNoStreet);

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

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

  it("throws when address city is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const companyNoCity = { ...draftCompany, city: null };
    spies.select.mockReturnValueOnce(companyNoCity);

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

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

  it("throws when address postalCode is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const companyNoPostalCode = { ...draftCompany, postalCode: null };
    spies.select.mockReturnValueOnce(companyNoPostalCode);

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

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

  it("throws when address country is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const companyNoCountry = { ...draftCompany, country: null };
    spies.select.mockReturnValueOnce(companyNoCountry);

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

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