import { render, screen, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { MemoryRouter } from "react-router-dom"
import { API } from "@/api/API"
import { MEMORY_ROUTER_TEST_FUTURE } from "@/testing/reactRouterTest"
import { DealerResignationDetailsPage } from "../pages/DealerResignationDetailsPage"

jest.mock("sonner", () => ({
    toast: {
        error: jest.fn(),
        success: jest.fn(),
    },
}))

jest.mock("@/api/API", () => ({
    API: {
        getResignationById: jest.fn(),
        getAuditLogs: jest.fn().mockResolvedValue({
            data: { success: true, data: [] },
        }),
        uploadResignationDocument: jest.fn(),
    },
}))

describe("DealerResignationDetailsPage", () => {
    const onBack = jest.fn()

    beforeEach(() => {
        jest.clearAllMocks()
    })

    function setup(resignationId = "missing") {
        render(
            <MemoryRouter future={MEMORY_ROUTER_TEST_FUTURE}>
                <DealerResignationDetailsPage
                    resignationId={resignationId}
                    onBack={onBack}
                />
            </MemoryRouter>,
        )
    }

    it("shows not found when resignation payload is absent", async () => {
        jest.mocked(API.getResignationById).mockResolvedValue({
            data: null,
        } as never)

        setup("id-404")

        expect(
            await screen.findByText(/resignation details not found/i),
        ).toBeInTheDocument()

        const user = userEvent.setup()
        await user.click(screen.getByRole("button", { name: /^back$/i }))
        expect(onBack).toHaveBeenCalled()
    })

    it("requests resignation by id", async () => {
        jest.mocked(API.getResignationById).mockResolvedValue({
            data: null,
        } as never)

        setup("res-abc-123")

        await waitFor(() => {
            expect(API.getResignationById).toHaveBeenCalledWith("res-abc-123")
        })
    })
})
