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,
  InvalidLegalNameError,
  CurrencyNotFoundError,
  CurrencyImmutableError,
} from "../lib/errors.generated";
import { draftCompany, activeCompany, inactiveCompany } from "../testing/fixtures";
import { run } from "./updateCompany";

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

const deps = { getCurrency };

describe("updateCompany", () => {
  it("updates legal name on DRAFT company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedCompany = { ...draftCompany, legalName: "New Name" };
    mock.enqueueResults([draftCompany], [updatedCompany]);

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

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

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

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

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

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

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

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

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

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

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