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

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

const deps = { getCurrency };

describe("activateCompany", () => {
  it("activates DRAFT company with all required fields", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activatedCompany = { ...draftCompany, status: "ACTIVE" };
    mock.enqueueResults(
      [draftCompany], // company lookup
      [{ id: "currency-usd", status: "ACTIVE" as const }], // getCurrency
      [activatedCompany],
    );

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeCompany]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveCompany]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const companyNoLegalName = { ...draftCompany, legalName: "" };
    mock.enqueueResults([companyNoLegalName]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftCompanyNoCurrency]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [draftCompany], // company lookup
      [], // getCurrency returns null
    );

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [draftCompany], // company lookup
      [{ id: "currency-usd", status: "INACTIVE" as const }], // getCurrency inactive
    );

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const companyNoStreet = { ...draftCompany, street: null };
    mock.enqueueResults([companyNoStreet]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const companyNoCity = { ...draftCompany, city: null };
    mock.enqueueResults([companyNoCity]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const companyNoPostalCode = { ...draftCompany, postalCode: null };
    mock.enqueueResults([companyNoPostalCode]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const companyNoCountry = { ...draftCompany, country: null };
    mock.enqueueResults([companyNoCountry]);

    const result = await mock.withTx((trx) =>
      run(trx, { companyId: companyNoCountry.id }, ctx, deps),
    );

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