import { screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi, beforeEach } from "vitest";
import ProductionStockReport from "./ProductionStockReport";
import { renderWithQueryClient as render } from "./test-utils";
import { ReportsAPI } from "@/apis/ReportsAPI";

vi.mock("@/apis/ReportsAPI", () => ({
  ReportsAPI: { getProductionCriticalStock: vi.fn() },
}));

const dateRange = { startDate: "2026-08-01", endDate: "2026-08-31" };

describe("ProductionStockReport", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("muestra el loader mientras carga", () => {
    ReportsAPI.getProductionCriticalStock.mockReturnValue(new Promise(() => {}));
    render(<ProductionStockReport companyId={1} dateRange={dateRange} onDataReady={vi.fn()} />);
    expect(document.querySelector(".animate-spin")).toBeTruthy();
  });

  it("muestra vacío cuando no hay stock crítico", async () => {
    ReportsAPI.getProductionCriticalStock.mockResolvedValue([]);
    render(<ProductionStockReport companyId={1} dateRange={dateRange} onDataReady={vi.fn()} />);
    expect(await screen.findByText(/No hay stock crítico en este momento/i)).toBeInTheDocument();
  });

  it("no consulta cuando falta companyId", () => {
    render(<ProductionStockReport companyId={undefined} dateRange={dateRange} onDataReady={vi.fn()} />);
    expect(ReportsAPI.getProductionCriticalStock).not.toHaveBeenCalled();
  });

  it("renderiza SKU, stock, mínimo y déficit", async () => {
    const onDataReady = vi.fn();
    ReportsAPI.getProductionCriticalStock.mockResolvedValue([
      { id: 11, sku: "SKU-CRIT", name: "Esencia crítica", stock: 1, min_stock: 5, deficit: 4 },
    ]);

    render(<ProductionStockReport companyId={1} dateRange={dateRange} onDataReady={onDataReady} />);

    expect(await screen.findByText("SKU-CRIT")).toBeInTheDocument();
    expect(screen.getByText("Esencia crítica")).toBeInTheDocument();
    expect(screen.getByText("Stock crítico y necesidades de producción")).toBeInTheDocument();
    await waitFor(() => expect(onDataReady).toHaveBeenCalled());
  });
});
