import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { RowEditForm } from "./RowEditForm";

describe("RowEditForm", () => {
  it("shows a diff preview before saving a sensitive record", async () => {
    const onSave = vi.fn().mockResolvedValue(undefined);

    render(
      <RowEditForm
        columns={[
          { id: "first_name", label: "First name" },
          { id: "email", label: "Email" },
        ]}
        editableFields={["first_name"]}
        onSave={onSave}
        record={{
          email: "test_owner@example.com",
          first_name: "Test",
          id: "user-1",
        }}
      />
    );

    fireEvent.change(screen.getByLabelText(/first name/i), {
      target: { value: "Ada" },
    });
    fireEvent.click(screen.getByRole("button", { name: /review changes/i }));

    expect(await screen.findByText(/before/i)).toBeInTheDocument();
    expect(screen.getByText(/after/i)).toBeInTheDocument();
    expect(screen.getByText(/first name:\s*test/i)).toBeInTheDocument();
    expect(screen.getByText(/first name:\s*ada/i)).toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: /confirm update/i }));

    await waitFor(() =>
      expect(onSave).toHaveBeenCalledWith({
        first_name: "Ada",
      })
    );
  });
});
