import React from "react";
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { api } from "./api";
import CompaniesTable from "./components/CompaniesTable";
import { I18nProvider } from "./i18n/I18nProvider";
import { ToastProvider } from "./toast";

jest.mock("./api", () => ({
  api: { get: jest.fn(), put: jest.fn() },
  getApiErrorMessage: (_error: unknown, fallback: string) => fallback,
}));
const mockedApi = api as jest.Mocked<typeof api>;

test("opens one company relationship view with applications and recent contact", async () => {
  const company = { id: 3, name: "Acme", recruiterName: "Rita", recruiterEmail: "rita@example.test" };
  mockedApi.get.mockImplementation((url) => Promise.resolve({ data: String(url).endsWith("/relationship") ? {
    company,
    applications: [{ id: 9, jobTitle: "Backend Developer", status: "Interview", messageCount: 1 }],
    recentContacts: [{ id: 12, jobApplicationId: 9, jobTitle: "Backend Developer", date: "2026-08-10T10:00:00Z", channel: "email", subject: "Interview", from: "Rita" }],
  } : [company] } as any));

  render(<I18nProvider><ToastProvider><MemoryRouter><CompaniesTable /></MemoryRouter></ToastProvider></I18nProvider>);
  fireEvent.click(await screen.findByRole("button", { name: "Relationship history: Acme" }));

  expect(await screen.findByText("Applications at this company")).toBeInTheDocument();
  expect(screen.getAllByText("Backend Developer").length).toBeGreaterThan(0);
  expect(screen.getByText(/Interview · 1 messages/)).toBeInTheDocument();
  expect(mockedApi.get).toHaveBeenCalledWith("/companies/3/relationship");
});
