import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidNameError,
  InvalidPartnerTypeError,
  CurrencyNotFoundError,
} from "../lib/errors.generated";
import { baseDraftPartner } from "../testing/fixtures";
import { getCompany } from "../../organization/query/getCompany.generated";
import { getCurrency } from "../../primitives/query/getCurrency.generated";
import { run } from "./createPartner";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("createPartner", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["business-partner:createPartner"],
  };

  it("creates partner in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const company = { id: "company-1" };
    const createdPartner = { ...baseDraftPartner, id: "new-partner-id" };

    spies.select.mockReturnValueOnce(company); // Company lookup
    spies.insert.mockReturnValue(createdPartner);

    const result = await run(
      db,
      { name: "Acme Corp", type: "ORGANIZATION", companyId: "company-1" },
      ctx,
      { getCompany },
      { getCurrency },
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.partner.status).toBe("DRAFT");
    }
    expect(spies.insert).toHaveBeenCalled();
  });

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

    const result = await run(
      db,
      { name: "Acme Corp", type: "ORGANIZATION", companyId: "nonexistent" },
      ctx,
      { getCompany },
      { getCurrency },
    );

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

  it("returns error when type is invalid", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(
      db,
      { name: "Acme Corp", type: "INVALID" as "ORGANIZATION", companyId: "company-1" },
      ctx,
      { getCompany },
      { getCurrency },
    );

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

  it("returns error when name is empty", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(
      db,
      { name: "", type: "ORGANIZATION", companyId: "company-1" },
      ctx,
      { getCompany },
      { getCurrency },
    );

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

  it("creates partner without preferred currency", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const company = { id: "company-1" };
    const createdPartner = { ...baseDraftPartner, id: "new-partner-id", preferredCurrencyId: null };

    spies.select.mockReturnValueOnce(company); // Company lookup
    spies.insert.mockReturnValue(createdPartner);

    const result = await run(
      db,
      { name: "Acme Corp", type: "ORGANIZATION", companyId: "company-1" },
      ctx,
      { getCompany },
      { getCurrency },
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.partner.preferredCurrencyId).toBeNull();
    }
  });

  it("creates partner with preferred currency", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const company = { id: "company-1" };
    const currency = { id: "currency-usd", code: "USD" };
    const createdPartner = {
      ...baseDraftPartner,
      id: "new-partner-id",
      preferredCurrencyId: "currency-usd",
    };

    spies.select
      .mockReturnValueOnce(company) // Company lookup
      .mockReturnValueOnce(currency); // Currency lookup
    spies.insert.mockReturnValue(createdPartner);

    const result = await run(
      db,
      {
        name: "Acme Corp",
        type: "ORGANIZATION",
        companyId: "company-1",
        preferredCurrencyId: "currency-usd",
      },
      ctx,
      { getCompany },
      { getCurrency },
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.partner.preferredCurrencyId).toBe("currency-usd");
    }
  });

  it("returns error when currency not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const company = { id: "company-1" };

    spies.select
      .mockReturnValueOnce(company) // Company lookup
      .mockReturnValueOnce(undefined); // Currency not found

    const result = await run(
      db,
      {
        name: "Acme Corp",
        type: "ORGANIZATION",
        companyId: "company-1",
        preferredCurrencyId: "nonexistent",
      },
      ctx,
      { getCompany },
      { getCurrency },
    );

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