import { render, screen, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { MemoryRouter, Routes, Route } from "react-router-dom"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { DomainDiffPage } from "./DomainDiffPage"
import { api } from "@/api/client"
import { vi } from "vitest"

function renderPage() {
  const qc = new QueryClient()
  return render(
    <QueryClientProvider client={qc}>
      <MemoryRouter initialEntries={["/domains/d1"]}>
        <Routes><Route path="/domains/:id" element={<DomainDiffPage />} /></Routes>
      </MemoryRouter>
    </QueryClientProvider>,
  )
}

test("apply sends applyPrunes=false by default, true only after opting in", async () => {
  vi.spyOn(api, "checkDomain").mockResolvedValue({
    updates: [{ kind: "update", type: "A", name: "a.", desired: ["1"], actual: ["2"], readOnly: false }],
    prunes: [{ kind: "delete", type: "A", name: "b.", actual: ["3"], readOnly: false }],
    readOnly: [], inSyncCount: 0,
  })
  const applySpy = vi.spyOn(api, "applyDomain").mockResolvedValue({ updates: [], prunes: [], readOnly: [], inSyncCount: 0 })
  const user = userEvent.setup()
  renderPage()

  const applyBtn = await screen.findByRole("button", { name: /apply/i })
  await user.click(applyBtn)
  await waitFor(() => expect(applySpy).toHaveBeenCalled())
  expect(applySpy.mock.calls[0][1]).toEqual({ applyUpdates: true, applyPrunes: false })

  // включить prune и применить снова
  const pruneToggle = screen.getByRole("checkbox", { name: /prune|удал/i })
  await user.click(pruneToggle)
  await user.click(screen.getByRole("button", { name: /apply/i }))
  await waitFor(() => expect(applySpy).toHaveBeenCalledTimes(2))
  expect(applySpy.mock.calls[1][1]).toEqual({ applyUpdates: true, applyPrunes: true })
})
