import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";
import App from "../src/App";

const { usersList, usersUpdate } = vi.hoisted(() => ({
  usersList: vi
    .fn()
    .mockResolvedValue([
      { id: 1, name: "Alice", defaultHourlyRateCents: 9500 },
    ]),
  usersUpdate: vi.fn().mockResolvedValue({
    id: 1,
    name: "Alice Updated",
    defaultHourlyRateCents: 12000,
  }),
}));

vi.mock("../src/lib/api", () => ({
  api: {
    users: { list: usersList, update: usersUpdate },
    projects: { list: vi.fn().mockResolvedValue([]) },
    reports: {
      weekly: vi.fn().mockResolvedValue({
        days: [],
        weekTotalMinutes: 0,
        weekTotalCostCents: 0,
      }),
    },
    timeEntries: {
      list: vi.fn().mockResolvedValue([]),
      create: vi.fn(),
      update: vi.fn(),
      delete: vi.fn(),
    },
  },
}));

describe("TopBar", () => {
  it("edits selected user default rate", async () => {
    render(
      <MemoryRouter initialEntries={["/weekly"]}>
        <App />
      </MemoryRouter>,
    );

    await waitFor(() => expect(usersList).toHaveBeenCalled());

    fireEvent.click(screen.getByRole("button", { name: "Edit user" }));
    const rateInput = screen.getByLabelText("Default rate (EUR/h)");
    fireEvent.change(rateInput, { target: { value: "120" } });
    fireEvent.click(screen.getByRole("button", { name: "Save" }));

    await waitFor(() =>
      expect(usersUpdate).toHaveBeenCalledWith(1, {
        name: "Alice",
        defaultHourlyRateCents: 12000,
      }),
    );
  });
});
