import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { VendorsTable } from "@/app/(portal)/inventory/vendors/vendors-table";

vi.mock("next/navigation", () => ({
  useRouter: () => ({ push: vi.fn() }),
}));

type Row = Parameters<typeof VendorsTable>[0]["vendors"][number];

const makeRow = (over: Partial<Row> = {}): Row => ({
  id: "v1",
  name: "Acme Marine Supplies",
  vendorId: "VND-001",
  gstin: null,
  address: null,
  isVerified: false,
  itemCount: 0,
  primaryContact: null,
  distanceKm: null,
  ...over,
});

describe("VendorsTable — vendor id (issue #57)", () => {
  it("renders the vendorId next to the name when present", () => {
    render(<VendorsTable vendors={[makeRow()]} hasSite={false} />);
    expect(screen.getByText("Acme Marine Supplies")).toBeTruthy();
    expect(screen.getByText("VND-001")).toBeTruthy();
  });

  it("omits the id (no placeholder) when vendorId is null", () => {
    render(<VendorsTable vendors={[makeRow({ vendorId: null })]} hasSite={false} />);
    expect(screen.queryByText("VND-001")).toBeNull();
  });

  it("filters by vendorId", () => {
    const rows = [
      makeRow({ id: "v1", name: "Acme Marine Supplies", vendorId: "VND-001" }),
      makeRow({ id: "v2", name: "Beta Traders", vendorId: "VND-999" }),
    ];
    render(<VendorsTable vendors={rows} hasSite={false} />);
    const search = screen.getByPlaceholderText(/Search by name/i);
    fireEvent.change(search, { target: { value: "VND-999" } });
    expect(screen.queryByText("Acme Marine Supplies")).toBeNull();
    expect(screen.getByText("Beta Traders")).toBeTruthy();
  });

  it("still filters by name", () => {
    const rows = [
      makeRow({ id: "v1", name: "Acme Marine Supplies", vendorId: "VND-001" }),
      makeRow({ id: "v2", name: "Beta Traders", vendorId: "VND-999" }),
    ];
    render(<VendorsTable vendors={rows} hasSite={false} />);
    const search = screen.getByPlaceholderText(/Search by name/i);
    fireEvent.change(search, { target: { value: "beta" } });
    expect(screen.getByText("Beta Traders")).toBeTruthy();
    expect(screen.queryByText("Acme Marine Supplies")).toBeNull();
  });

  it("advertises ID search in the placeholder", () => {
    render(<VendorsTable vendors={[makeRow()]} hasSite={false} />);
    expect(screen.getByPlaceholderText(/Search by name, ID, GSTIN or address/i)).toBeTruthy();
  });
});
